您的位置:首页 > 其它

hdu 1026(优先队列+BFS)

2013-05-03 09:56 260 查看
点击打开链接

分析:

刚开始直接BFS。但是WAN次。。。,后来看到讨论区里的数据,才发现要用优先队列的。。。

注意second课能为单数。

注意起点和终点都有怪兽。。

#include"stdio.h"
#include"string.h"
#include"stdlib.h"
#include"queue"
using namespace std;
struct node
{
int x,y;
int step;
int cnt;
friend bool operator <(node a,node b)
{
return a.step>b.step;
}
};
int way[100001][2],t;
struct node p,q,o;
char map[111][111];
int n,m,pre[100001];
int mark[111][111];
int dir[4][2]={1,0,0,1,-1,0,0,-1};

int judge(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m&&!mark[x][y]&&map[x][y]!='X')
return 1;
return 0;
}

void bfs()
{
int i,j,k,x,y;
priority_queue<node>Q;
t=0;
p.x=n-1;
p.y=m-1;
p.step=0;
p.cnt=t;
pre[0]=-1;
way[t][0]=p.x;
way[t][1]=p.y;
mark[p.x][p.y]=1;
t++;
o=p;
if(map[p.x][p.y]>='0'&&map[p.x][p.y]<='9')
{
for(i=0;i<map[p.x][p.y]-'0';i++)
{
p.step=o.step+1;
p.cnt=t++;
pre[p.cnt]=o.cnt;
way[p.cnt][0]=p.x;
way[p.cnt][1]=p.y;
o=p;
}
}
Q.push(p);
while(!Q.empty())
{
p=Q.top();
Q.pop();
if(p.x==0&&p.y==0)
{
if(p.step!=1)
printf("It takes %d seconds to reach the target position, let me show you the way.\n",p.step);
else
printf("It takes %d second to reach the target position, let me show you the way.\n",p.step);

i=p.cnt;k=1;
while(i)
{
j=pre[i];
if(way[i][0]==way[j][0]&&way[i][1]==way[j][1])
printf("%ds:FIGHT AT (%d,%d)\n",k,way[i][0],way[i][1]);
else printf("%ds:(%d,%d)->(%d,%d)\n",k,way[i][0],way[i][1],way[j][0],way[j][1]);
k++;
//if(k==p.step)break;
i=j;
}

return ;
}
for(i=0;i<4;i++)
{
q.x=x=p.x+dir[i][0];
q.y=y=p.y+dir[i][1];
if(judge(x,y))
{
mark[x][y]=1;
if(map[x][y]>='0'&&map[x][y]<='9')
{
o=p;
for(j=0;j<map[x][y]-'0'+1;j++)
{
q.step=o.step+1;
q.cnt=t++;
pre[q.cnt]=o.cnt;
way[q.cnt][0]=q.x;
way[q.cnt][1]=q.y;
o=q;
}
Q.push(q);
}
else if(map[x][y]=='.')
{
q.step=p.step+1;
q.cnt=t++;
pre[q.cnt]=p.cnt;
way[q.cnt][0]=q.x;
way[q.cnt][1]=q.y;
Q.push(q);
}
}
}
}
printf("God please help our poor hero.\n");
}

int main()
{
int i;
while(scanf("%d%d",&n,&m)!=-1)
{
getchar();
for(i=0;i<n;i++)
gets(map[i]);
memset(way,0,sizeof(way));
memset(mark,0,sizeof(mark));
memset(pre,0,sizeof(pre));
bfs();
printf("FINISH\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: