hdu 1242

在使用优先队列时, 不仅可按元素的大小为优先级,在使用结构体时,可通过运算符重载

在其他的博客看到一句话,优先队列是队列和排序的结合,很精辟

本题因为经过守卫和道路时所花的时间不一样,故不能用简单的队列求解,可使用优先队列,到达该点时间少的先出队列

#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

struct node
{
	int x, y, t;
	friend bool operator < (const node a, const node b)
	  {
	  	return a.t > b.t;
	  }
};
int dx[] = {0, 0, 0, -1, 1};
int dy[] = {0, -1, 1, 0, 0};
int vis[210][210], n, m;
char maze[210][210];
int bfs(int x, int y)
{
	node a, b;
	priority_queue<node> q;
	while(!q.empty())  q.pop();
	a.x = x, a.y = y, a.t = 0;
	q.push(a);
	vis[x][y] = 1;
	while(!q.empty())
	  {
	  	 a = q.top();
	  	 q.pop();
	  	 if(maze[a.x][a.y] == 'r')
	  	 	return a.t;
	  	 for(int  i=1; i<=4; i++)
	  	   {
	  	   	 b.x = a.x + dx[i];
	  	   	 b.y = a.y + dy[i];
	  	   	 if(!vis[b.x][b.y] && b.x>=1 && b.x<=n && b.y>=1 && b.y<=m && maze[b.x][b.y]!='#')
	  	   	   {
	  	   	   	 vis[b.x][b.y] = 1;
	  	   	   	 if(maze[b.x][b.y] == 'x')
	  	   	   	 	b.t = a.t + 2;
	  	   	   	  else 
	  	   	   	  	b.t = a.t + 1;
	  	   	   	  q.push(b);
	  	   	   }
	  	   }
	  }
	return -1;
}
int main()
{
	while(scanf("%d %d", &n, &m) == 2)
	  {
	  	 int sx, sy;
	  	 for(int i=1; i<=n; i++)
	  	 	scanf("%s", maze[i] + 1);
  	 	 
	  	 for(int i=1; i<=n; i++)
	  	 	for(int j=1; j<=m; j++)
	  	 	  {
	  	 	  	 vis[i][j] = 0;
	  	 	  	 if(maze[i][j] == 'a')
	  	 	  	   {
	  	 	  	   	  sx = i;
	  	 	  	   	  sy = j;
	  	 	  	   }
	  	 	  }
	  	 int ans=  bfs(sx, sy);
	  	 if(ans == -1)
	  	 	printf("Poor ANGEL has to stay in the prison all his life.\n");
	  	 else
	  	 	printf("%d\n", ans);
	  }
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值