hdu 1242

来源:互联网 发布:网络粑粑什么意思 编辑:程序博客网 时间:2024/06/01 08:21

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

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

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

#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;}


0 0
原创粉丝点击