HDU 1026

时间:2023-03-09 01:58:22
HDU 1026

http://acm.hdu.edu.cn/showproblem.php?pid=1026

记录bfs路径,用一个数组记录next前驱的方向,然后递归的时候减回去即可

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue> using namespace std ;
const int INF=0xfffffff; int n,m;
char M[][]; struct node{
int x,y,step;
friend bool operator <(node a,node b){
return a.step>b.step;
}
}; int dx[]={,-,,};
int dy[]={,,,-};
int vis[][]; int rd[][]; int bfs(){
memset(vis,,sizeof(vis));
priority_queue <node> q;
node s;
s.x=;s.y=;s.step=;
if(M[][]!='X' && M[n-][m-]!='X')q.push(s);
while(!q.empty()){
node u=q.top();
q.pop();
if(u.x==n- && u.y==m-)return u.step;
for(int i=;i<;i++){
int xx=u.x+dx[i];
int yy=u.y+dy[i];
if(xx< || xx>=n || yy< || yy>=m)continue;
if(M[xx][yy]=='X')continue;
if(vis[xx][yy])continue;
vis[xx][yy]=;
node next=u;
next.x=xx;next.y=yy;next.step++;
if(M[xx][yy]>='' && M[xx][yy]<='')
next.step+=(M[xx][yy]-'');
rd[xx][yy]=i;
q.push(next);
}
}
return INF;
}
int tt;
void output(int x,int y){
if(rd[x][y]==-)return;
int xx=x-dx[rd[x][y]];
int yy=y-dy[rd[x][y]];
output(xx,yy);
printf("%ds:(%d,%d)->(%d,%d)\n",tt++,xx,yy,x,y);
if(M[x][y]>='' && M[x][y]<=''){
int nn=M[x][y]-'';
while(nn--){
printf("%ds:FIGHT AT (%d,%d)\n",tt++,x,y);
}
}
} int main(){
while(~scanf("%d%d",&n,&m)){
for(int i=;i<n;i++)
scanf("%s",M[i]);
int ans=bfs();
if(ans==INF)puts("God please help our poor hero.");
else{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
rd[][]=-;
tt=;
output(n-,m-);
}
puts("FINISH");
}
return ;
}