hdu 1429 勝利大逃亡(續(xù)) bfs+狀態(tài)壓縮
來源:程序員人生 發(fā)布時(shí)間:2015-03-20 08:25:56 閱讀次數(shù):2719次
成功大流亡(續(xù))
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5738 Accepted Submission(s): 2006
Problem Description
Ignatius再次被魔王抓走了(弄不懂他咋這么討魔王喜歡)……
這次魔王汲取了上次的教訓(xùn),把Ignatius關(guān)在1個(gè)n*m的地牢里,并在地牢的某些地方安裝了帶鎖的門,鑰匙藏在地牢另外的某些地方。剛開始Ignatius被關(guān)在(sx,sy)的位置,離開地牢的門在(ex,ey)的位置。Ignatius每分鐘只能從1個(gè)坐標(biāo)走到相鄰4個(gè)坐標(biāo)中的其中1個(gè)。魔王每t分鐘回地牢視察1次,若發(fā)現(xiàn)Ignatius不在原位置便把他拎回去。經(jīng)過若干次的嘗試,Ignatius已畫出全部地牢的地圖。現(xiàn)在請(qǐng)你幫他計(jì)算能否再次成功流亡。只要在魔王下次視察之前走到出口就算離開地牢,如果魔王回來的時(shí)候恰好走到出口或還未到出口都算流亡失敗。
Input
每組測(cè)試數(shù)據(jù)的第1行有3個(gè)整數(shù)n,m,t(2<=n,m<=20,t>0)。接下來的n行m列為地牢的地圖,其中包括:
. 代表路
* 代表墻
@ 代表Ignatius的起始位置
^ 代表地牢的出口
A-J 代表帶鎖的門,對(duì)應(yīng)的鑰匙分別為a-j
a-j 代表鑰匙,對(duì)應(yīng)的門分別為A-J
每組測(cè)試數(shù)據(jù)之間有1個(gè)空行。
Output
針對(duì)每組測(cè)試數(shù)據(jù),如果可以成功流亡,請(qǐng)輸出需要多少分鐘才能離開,如果不能則輸出⑴。
Sample Input
4 5 17
@A.B.
a*.*.
*..*^
c..b*
4 5 16
@A.B.
a*.*.
*..*^
c..b*
Sample Output
16
⑴
Author
LL
做法:由于鑰匙最多有10把,2^10 =1024,所以可以把10把鑰匙有無的情況記錄在 1個(gè)數(shù)中。 num的第3維就是 鑰匙 具有的狀態(tài)。然后就和普通的bfs1樣了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <malloc.h>
#include <ctype.h>
#include <math.h>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#include <stack>
#include <queue>
#include <vector>
#include <deque>
#include <set>
#include <map>
using namespace std;
int n,m,t;
char mp[22][22];
int num[22][22][1050];//位置 鑰匙狀態(tài)
int dir[4][2]={⑴,0,1,0,0,1,0,⑴};
int ex,ey;
int stax,stay;
struct point
{
int x,y,step,key;
};
int ok(int x,int y)
{
if(!(x>=0&&x<n&&y>=0&&y<m))
return 0;
char ch=mp[x][y];
if(ch<='J'&&ch>='A')
return 3; //門
if(ch<='j'&&ch>='a')
return 2; //key
if(ch!='*')
return 1;
return 0;
}
int bfs()
{
if(t==0)
return ⑴;
point sta,now,tem;
sta.x=stax;
sta.y=stay;
sta.step=0;
sta.key=0;
queue<point> q;
q.push(sta);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.step!=0&&now.step%t==0)
{
return ⑴;
//now.x=stax;
//now.y=stay;
}
if(now.x==ex&&now.y==ey)
return now.step;
for(int i=0;i<4;i++)
{
int xx=now.x+dir[i][0];
int yy=now.y+dir[i][1];
int cdt=ok(xx,yy);//condition
int key=now.key;
if(cdt==0)
continue;
if(cdt==3&&(key&(1<<(mp[xx][yy]-'A')))==0)
continue;
if(cdt==2)
key|=(1<<(mp[xx][yy]-'a'));
if(num[xx][yy][key]==⑴||num[xx][yy][key]>now.step+1)
{
tem.x=xx;
tem.y=yy;
tem.step=now.step+1;
tem.key=key;
num[xx][yy][key]=now.step+1;
q.push(tem);
}
}
}
return ⑴;
}
int main()
{
while(scanf("%d%d%d",&n,&m,&t)!=EOF)
{
memset(num,⑴,sizeof num);
for(int i=0;i<n;i++)
scanf("%s",mp[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mp[i][j]=='@')
stax=i,stay=j;
if(mp[i][j]=='^')
ex=i,ey=j;
}
}
printf("%d
",bfs());
}
return 0;
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)