优先队列 + bfs

题目链接:hdu 1242.

Rescue

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 41594
Accepted Submission(s): 14244

Problem 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

为什么不能直接bfs,而要优先队列优化呢?

因为每次我们走到守卫的位置时,我们需要两步,但是我们并不能马上扩充这个点。

所以以下AC代码:

#include<bits/stdc++.h>
using namespace std;
const int N=210;
const int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
int n,m,dst[N][N],tx,ty;
char g[N][N];
struct node
{
	int x,y,t;
};
priority_queue<node> pq;
bool operator<(const node a,const node b)
{
	return a.t>b.t;
}
int check(int x,int y)
{
	if(x>=1&&x<=n&&y>=1&&y<=m&&!dst[x][y]&&g[x][y]!='#')	return 1;
	return 0;
}
int bfs()
{
	while(pq.size())	pq.pop();
	pq.push({tx,ty,1});
	dst[tx][ty]=1;
	while(pq.size())
	{
		node p=pq.top();
		pq.pop();
		if(g[p.x][p.y]=='r')	return dst[p.x][p.y];
		for(int i=0;i<4;i++)
		{
			int tx=p.x+dx[i];
			int ty=p.y+dy[i];
			if(check(tx,ty))
			{
				dst[tx][ty]=dst[p.x][p.y]+1;
				if(g[tx][ty]=='x')	dst[tx][ty]++;
				pq.push({tx,ty,dst[tx][ty]});
			}
		}
	}
	return 0;
}
int main()
{
	while(cin>>n>>m)
	{
		memset(dst,0,sizeof dst);
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++)
			{
				cin>>g[i][j];
				if(g[i][j]=='a')	tx=i,ty=j;
			}
		int res=bfs();
		if(res)	cout<<res-1<<endl;
		else	cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
	}
	return 0;
}