标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 16456 Accepted Submission(s):
5221
Special Judge
#include<iostream> #include<cstdio> #include<cstring> #include<stack> #include<queue> using namespace std; #define INF 999999999 struct Node { int x,y; int tim; friend bool operator<(Node a,Node b) { return a.tim>b.tim; } }; char map[105][105]; int dir[4][2]= {{-1,0},{0,1},{1,0},{0,-1}}; int flag[105][105]; int vis[105][105]; int n,m; bool inside(Node nn) { if(nn.x>=0&&nn.x<n&&nn.y>=0&&nn.y<m) return 1; return 0; } int ans=INF; priority_queue<Node> pq; int bfs() { Node sta; sta.x=0; sta.y=0; sta.tim=0; pq.push(sta); vis[sta.x][sta.y]=1; while(!pq.empty()) { Node now=pq.top(); if(now.x==n-1&&now.y==m-1) return 1; pq.pop(); for(int i=0;i<4;i++) { Node next; next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; if(!vis[next.x][next.y]&&inside(next)&&map[next.x][next.y]!=‘X‘) { flag[next.x][next.y]=i+1; if(map[next.x][next.y]==‘.‘) next.tim=now.tim+1; else next.tim=now.tim+1+map[next.x][next.y]-‘0‘; pq.push(next); vis[next.x][next.y]=1; } } } return 0; } void printpath(int x,int y,int time) { if(flag[x][y]==0) return; int add=0; if(map[x][y]!=‘.‘) add=map[x][y]-‘0‘; printpath(x-dir[flag[x][y]-1][0],y-dir[flag[x][y]-1][1],time-1-add); if(map[x][y]!=‘.‘) { printf("%ds:(%d,%d)->(%d,%d)\n",time-add,x-dir[flag[x][y]-1][0],y-dir[flag[x][y]-1][1],x,y); for(int i=1;i<=map[x][y]-‘0‘;i++) printf("%ds:FIGHT AT (%d,%d)\n",time-add+i,x,y);} else printf("%ds:(%d,%d)->(%d,%d)\n",time,x-dir[flag[x][y]-1][0],y-dir[flag[x][y]-1][1],x,y); } int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(vis,0,sizeof(vis)); memset(flag,0,sizeof(flag)); while(!pq.empty()) pq.pop(); memset(vis,0,sizeof(vis)); for(int i=0; i<n; i++) scanf("%s",map[i]); int findit=bfs(); if(findit) { printf("It takes %d seconds to reach the target position, let me show you the way.\n",pq.top().tim); printpath(pq.top().x,pq.top().y,pq.top().tim); } else printf("God please help our poor hero.\n"); printf("FINISH\n"); } return 0; }
HDU_1026_Ignatius and the Princess I_BFS(保存路径)
标签:
原文地址:http://www.cnblogs.com/jasonlixuetao/p/5531846.html