营救天使(优先队列)

http://www.cnblogs.com/summerRQ/articles/2470130.html
普通队列的出队方式是对头出列
优先队列这则是按照一定的优先级出队的就好比医院里面急诊病人优先看病
看下面一道题可以帮助理解优先队列
http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1335

/*
题意:
a被困在监狱他的朋友r想要去救他 里面有士兵x遇到士兵时r可以杀掉他,但是会耗时一分钟
,结果要输出救到a的最少时间

注意:
4 3
.r#
.x#
.##
a##
有一种情况是不走x比走x花费的时间少,,()坑

*/

include

include<string.h>

include

include<stdio.h>

include<stdlib.h>

include<math.h>

const int XY=205;
char miGong[XY][XY];
int vis[XY][XY];
int dir[4][2]= {0,1,1,0,0,-1,-1,0};
int m,n;
using namespace std;
struct note
{
int x;
int y;
int s;
friend bool operator <(note n1,note n2)//自己定义一种优先级
{
return n1.s>n2.s;//时间少的优先级高(注意大于或小于号)
}
};
int bfs(int sx,int sy,int ex,int ey)
{
memset(vis,0,sizeof(vis));
note a;
a.x=sx;
a.y=sy;
a.s=0;
vis[sx][sy]=1;
priority_queueq;
q.push(a);
while(!q.empty())
{
a=q.top();//注意不是q.front();
q.pop();
// cout<<miGong[a.x][a.y]<<" ";
if(a.xex&&a.yey)return a.s;
for(int i=0; i<4; i++)
{
int tx=a.x+dir[i][0];
int ty=a.y+dir[i][1];
if(tx<0||ty<0||tx>=m||ty>=n)
continue;
if(miGong[tx][ty]!='#'&&vis[tx][ty]0)
{
vis[tx][ty]=1;
note b;
b.x=tx;
b.y=ty;
if(miGong[tx][ty]
'x')
b.s=a.s+2;
else b.s=a.s+1;
q.push(b);
}
}
}
return -1;
}
int main()
{

while(~scanf("%d%d",&m,&n))
{
    memset(miGong,0,sizeof(miGong));
    int startX,startY,endX,endY;
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
        {
            scanf(" %c",&miGong[i][j]);
            if(miGong[i][j]=='r')
            {
                startX=i;
                startY=j;
            }
            if(miGong[i][j]=='a')
            {
                endX=i;
                endY=j;
            }
        }
    int b=bfs(startX,startY,endX,endY);
    if(b==-1 )
        printf("Poor ANGEL has to stay in the prison all his life.\n");
    else
        printf("%d\n",b);
}
return 0;

}

/*
4 3
.r#
.x#
.##
a##

*/

posted @ 2016-03-21 19:22  -梦里不知身是客  阅读(244)  评论(0)    收藏  举报