HDU 1242 Rescue(BFS +优先队列)

来源:互联网 发布:淘宝关联销售模板 编辑:程序博客网 时间:2024/05/01 23:17

题目大意:一个娃被关在监狱里了,他的好基友们前来营救。碰到壮丁就花个一分钟的时间杀掉。每走一步又要花费一分钟。问他的朋友救到他要多久。注意:他有好多基友。

思路:因为有好多基友,所以就用倒着推。让他去找基友。碰到壮丁STEP+=2   否则就+1。。找到以后就可以丢肥皂了。

#include <iostream>#include <cstdio>#include <queue>#include <vector>#include <cstring>using namespace std;struct node{    int x,y;    int step;    bool operator <(const node &a) const   //定义什么叫小   就是步骤大的优先级小    {        return step > a.step;    }};int dx[]= {0,0,-1,1};int dy[]= {1,-1,0,0};priority_queue<node>Q;int n,m;int v[205][205];int map[205][205];void bfs(){    node w,e;    while(!Q.empty())    {        w=Q.top();        Q.pop();        for(int k=0;k<4;k++)        {            e=w;            int xx=e.x+dx[k];            int yy=e.y+dy[k];            if(map[xx][yy]!=0 && v[xx][yy]==0)            {                v[xx][yy]=1;                e.x=xx;                e.y=yy;                if(map[xx][yy]==3)e.step+=2;                else e.step++;                if(map[xx][yy]==4){printf("%d\n",e.step);return;}                Q.push(e);            }        }    }    printf("Poor ANGEL has to stay in the prison all his life.\n");}int main(){    node w;    while(scanf("%d%d",&n,&m)!=EOF)    {        getchar();        while(!Q.empty())Q.pop();        memset(map,0,sizeof(map));        memset(v,0,sizeof(v));        char ch;        for(int i=1;i<=n;i++)        {            for(int j=1;j<=m;j++)            {scanf("%c",&ch);            if(ch=='#')map[i][j]=0;            else if(ch=='.')map[i][j]=1;            else if(ch=='a'){map[i][j]=2;w.x=i;w.y=j;}            else if(ch=='x')map[i][j]=3;            else if(ch=='r')map[i][j]=4;            }            getchar();        }        /*for(int i=1;i<=n;i++)        {            for(int j=1;j<=m;j++)            printf("%d",map[i][j]);            putchar(10);        }*/        v[w.x][w.y] = 1;        w.step=0;        Q.push(w);        bfs();    }    return 0;}/*7 8#.#####.#.a#..r.#..#x.....#.x#x##...##...#..............*/