HDU 1026 Ignatius and the Princess I
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026
题意:就是从左上角到又下角的最短距离,过程中有数字代表怪兽的HP。打一滴血要花费一步时间。
直接BFS就好了
AC代码:
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
struct node
{
int x,y,step;
int f;
bool operator <(const node &a) const
{
return step>a.step;
}
};
struct node front,next,res[110][110];
int n,m,cnt,k1,k2,rx,ry,ss;
int xx[4]={0,0,-1,1};
int yy[4]={-1,1,0,0};
char map[110][110];
bool vis[110][110];
int mark[110][110];
priority_queue<node>q;
int BFS(int x,int y,int ansx,int ansy)
{
int i,dx,dy,k=-1;
memset(vis,false,sizeof vis);
if(x==ansx && y==ansy)
return 0;
front.x=x;
front.y=y;
front.step=0;
vis[x][y]=true;
q.push(front);
while(!q.empty())
{
front=q.top();
q.pop();
for(i=0;i<4;i++)
{
dx=front.x+xx[i];
dy=front.y+yy[i];
if(dx>=0 && dx<n && dy>=0 && dy<m && map[dx][dy]!='X' && !vis[dx][dy])
{
vis[dx][dy]=true;
next.x=dx;
next.y=dy;
next.step=front.step+mark[dx][dy]+1;
res[dx][dy].step=k;
res[dx][dy].f=mark[front.x][front.y];
res[dx][dy].x=front.x;
res[dx][dy].y=front.y;
if(dx==ansx && dy==ansy)
return next.step;
q.push(next);
}
}
k++;
}
return -1;
}
void print(int x,int y)
{
int i;
if(res[x][y].step!=(-1))
print(res[x][y].x,res[x][y].y);
if(res[x][y].f<1)
{
printf("%ds:",ss++);
printf("(%d,%d)->(%d,%d)\n",res[x][y].x,res[x][y].y,x,y);
}
else
{
for(i=0;i<res[x][y].f;i++)
{
printf("%ds:",ss++);
printf("FIGHT AT (%d,%d)\n",res[x][y].x,res[x][y].y);
}
printf("%ds:",ss++);
printf("(%d,%d)->(%d,%d)\n",res[x][y].x,res[x][y].y,x,y);
}
}
int main()
{
int i,j;
while(scanf("%d %d",&n,&m)!=EOF)
{
while(!q.empty())
q.pop();
memset(mark,0,sizeof mark);
memset(map,0,sizeof map);
memset(res,0,sizeof res);
for(i=0;i<n;i++)
scanf("%s",map[i]);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(map[i][j]>='0' && map[i][j]<='9')
mark[i][j]=map[i][j]-'0';
}
}
cnt=0;
k1=0,k2=-1;
rx=0,ry=0;
int ans=BFS(rx,ry,n-1,m-1);
if(ans==-1)
printf("God please help our poor hero.\n");
else
{
ss=1;
printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
print(n-1,m-1);
if(mark[n-1][m-1]>0)
{
for(i=0;i<mark[n-1][m-1];i++)
{
printf("%ds:",ss++);
printf("FIGHT AT (%d,%d)\n",n-1,m-1);
}
}
}
puts("FINISH");
}
return 0;
}
/*
3 3
...
.1X
.2.
5 6
......
......
......
.....X
....2.
*/