HDU 1026 Ignatius and the Princess I(BFS+优先队列)

来源:互联网 发布:歼20和f35哪个厉害知乎 编辑:程序博客网 时间:2024/05/16 08:42

卡了好久的题 伴随着我把实验室的电脑从win8->win10->Ubuntu
题意:从(0,0)到(n-1,m-1)的最短时间并打印路径

跟普通的BFS不一样的地方是每个位置会有怪兽,因此不能就简单的直接考虑路径,打怪兽的这个时间和另外的移动的时间要达到同步
(所以我WA了= =)
比较推荐的做法是用优先队列进行BFS,用时间作为优先的比较,按时间从小到大不断pop出来寻找下一个位置;
同时用pre数组记录当前顶点的前驱顶点的横纵坐标,记录第一次搜到该点时它的前驱顶点,当最后输出时从(0,0)开始输出当前位置的前驱顶点(所以bfs是从终点到起点的

所以过程是这样的:
从(n-1,m-1)开始bfs,走到下一个可行顶点(x,y)记录pre[x][y]=(n-1,m-1)
遇到有怪兽的地方只要把time增加再push进去即可(如果后来的时间比打怪兽的这条路小,那自然会优先到前面去)
直到走到(0,0),输出总时间后,打印路径:
pre[0][0]得到的(x,y)即是到达(0,0)前的那一步,pre[x][y]即是到达(x,y)前的那一步……依次类推,直到(n-1,m-1)
中间有怪兽的地方循环一下即可
如果没有可到达终点的路径就自动执行完循环到达函数最后,输出另一条语句即可

发现此类的题都爱用结构体并且的确方便了很多
所以pair要渐渐不用了吗~

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <queue>using namespace std;const int N=110;struct node {    int x,y;    int time;    node(int x,int y,int time):x(x),y(y),time(time) {}    node() {}};bool operator<(node a,node b) {//小的时间在top来不断使用     return a.time>b.time;}struct Pre {    int px,py;} pre[N][N];int n,m;char map[N][N];int vis[N][N];int dx[4]= {0,0,-1,1};int dy[4]= {1,-1,0,0};void bfs(int x,int y) {    priority_queue<node> q;    if(map[x][y]!='.') q.push(node(x,y,map[x][y]-'0'));    else q.push(node(x,y,0));    vis[x][y]=1;    pre[x][y].px=-1;//标记结束结点     while(!q.empty()){        node first=q.top();        q.pop();        if(first.x==0&&first.y==0){            int ans=first.time;            int t=1;            printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);            while(pre[first.x][first.y].px!=-1){                int prex=pre[first.x][first.y].px;                int prey=pre[first.x][first.y].py;                printf("%ds:(%d,%d)->(%d,%d)\n",t++,first.x,first.y,prex,prey);                if(map[prex][prey]!='.'){                    for(int i=0;i<map[prex][prey]-'0';i++){                        printf("%ds:FIGHT AT (%d,%d)\n",t++,prex,prey);                    }                }                first.x=prex,first.y=prey;            }            return ;        }        for(int i=0;i<4;i++){            node next;            next.x=first.x+dx[i],next.y=first.y+dy[i],next.time=first.time+1;            if(!vis[next.x][next.y]&&next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&map[next.x][next.y]!='X'){                       vis[next.x][next.y]=1;                if(map[next.x][next.y]!='.') next.time+=(map[next.x][next.y]-'0');                pre[next.x][next.y].px=first.x;//记录第一次搜到的前驱结点                pre[next.x][next.y].py=first.y;                q.push(next);            }        }    }    puts("God please help our poor hero.");}int main() {    while(~scanf("%d %d",&n,&m)) {        memset(vis,0,sizeof(vis));        for(int i=0; i<n; i++) {            scanf("%s",map[i]);        }        bfs(n-1,m-1);        puts("FINISH");    }    return 0;}
0 0