您的位置:首页 > 产品设计 > UI/UE

Rescue-优先队列

2015-07-21 18:59 363 查看
F - Rescue
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d
& %I64u
Submit Status Practice HDU
1242

Description

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up,
down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)

Input

First line contains two integers stand for N and M.

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.

Process to the end of the file.

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."

Sample Input

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........


Sample Output

13


/*
Author: 2486
Memory: 1536 KB		Time: 15 MS
Language: G++		Result: Accepted
Public:		No Yes
*/
//只要是设计到每一次需要取到最短的时间或者路径的问题时,就用优先队列,尤其是在存在不均一变化的情况下。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=200+5;
int n,m;
char maps[maxn][maxn];
bool vis[maxn][maxn];
int dx[]= {1,0,-1,0};
int dy[]= {0,1,0,-1};
int inx,iny;
struct stepss {
int x,y,steps;
stepss(int x,int y,int steps):x(x),y(y),steps(steps) {}
bool operator<(const stepss &a)const {
return steps>a.steps;
}
};
void bfs() {
priority_queue<stepss>G;/////////////////
G.push(stepss(inx,iny,0));
while(!G.empty()) {
stepss s=G.top();
G.pop();
if(s.x<0||s.y<0||s.x>=n||s.y>=m||maps[s.x][s.y]=='#'||vis[s.x][s.y])continue;
vis[s.x][s.y]=true;
if(maps[s.x][s.y]=='a') {
printf("%d\n",s.steps);
return ;
}
if(maps[s.x][s.y]=='x')s.steps++;
for(int i=0; i<4; i++) {
int nx=s.x+dx[i];
int ny=s.y+dy[i];
G.push(stepss(nx,ny,s.steps+1));
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main() {
//freopen("D://imput.txt","r",stdin);
while(~scanf("%d%d",&n,&m)) {
memset(vis,false,sizeof(vis));
for(int i=0; i<n; i++) {
scanf("%s",maps[i]);
for(int j=0; j<m; j++) {
if(maps[i][j]=='r') {
inx=i;
iny=j;
}
}
}
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: