hdu 1026(优先队列+BFS)

点击打开链接


分析:

刚开始直接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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值