标签:
Description
Input
Output
Sample Input
Sample Output
#include<stdio.h> #include<string.h> #include<vector> #include<map> #include<queue> #include<stack> #include<cstdio> #include<string> #include<math.h> #include<algorithm> #define LL long long #define PI atan(1.0)*4 #define DD double #define MAX 101 #define mod 10003 #define dian 1.000000011 #define INF 0x3f3f3f using namespace std; int head[MAX],ans; int n,m,t; char s[MAX][MAX]; int vis[MAX][MAX][20][1<<6]; int ke[15]; struct node { int x,y,key,time,snack; friend bool operator< (node a,node b) { return a.time>b.time; } }; int Move[4][2]={1,0,-1,0,0,1,0,-1}; int judge(int a,int b) { if(a>=0&&a<n&&b>=0&&b<n&&s[a][b]!=‘#‘) return 1; return 0; } int bfs(int x1,int y1) { int i; priority_queue<node>q; memset(vis,0,sizeof(vis)); while(!q.empty()) q.pop(); node beg,end; beg.x=x1; beg.y=y1; beg.time=0; beg.key=0; beg.snack=0; q.push(beg); vis[beg.x][beg.y][beg.key][beg.snack]=1; while(!q.empty()) { beg=q.top(); q.pop(); if(s[beg.x][beg.y]==‘T‘&&beg.key==m) { ans=beg.time; return 1; } for(i=0;i<4;i++) { end.x=beg.x+Move[i][0]; end.y=beg.y+Move[i][1]; if(judge(end.x,end.y)) { if(s[end.x][end.y]>=‘a‘&&s[end.x][end.y]<=‘z‘)//找到蛇 { end.snack=beg.snack; end.key=beg.key; int num=s[end.x][end.y]-‘a‘; if(end.snack&(1<<num))//判断蛇是否被杀死 end.time=beg.time+1; else end.time=beg.time+2; end.snack|=(1<<num);//将这条蛇加入已杀死的标记 } else if(s[end.x][end.y]>=‘1‘&&s[end.x][end.y]<=‘9‘)//找到钥匙 { end.snack=beg.snack; end.key=beg.key; end.time=beg.time+1; int num=s[end.x][end.y]-‘0‘; if(end.key+1==num)//判断是否找到了n之前的钥匙 end.key++; } else //路 { end.key=beg.key; end.snack=beg.snack; end.time=beg.time+1; } if(!vis[end.x][end.y][end.key][end.snack]) //判断当前位置是否标记 { vis[end.x][end.y][end.key][end.snack]=1; q.push(end); } } } } return 0; } int main() { int x1,y1,i,j,k; while(scanf("%d%d",&n,&m),n|m) { ans=0; for(i=0;i<n;i++) scanf("%s",s[i]); k=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(s[i][j]==‘K‘) { x1=i;y1=j; } if(s[i][j]==‘S‘) { s[i][j]=‘a‘+k++;//将不同的蛇标记出来 } } } if(bfs(x1,y1)) printf("%d\n",ans); else printf("impossible\n"); } return 0; }
hdu 5025 Saving Tang Monk(bfs+状态压缩)
标签:
原文地址:http://www.cnblogs.com/tonghao/p/5358729.html