• HDU 1242


    HDU 1242

    BFS + 优先队列 + 逆向思维

    注意多组输入

    题目中只有一个 (a) 但是可能有多个(r) ,所以可以从 (a-r) 这个来搜索

    因为(BFS)树的同一深度各个节点的值可能不同,所以要用优先队列,重载小于号

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <queue>
    #include <cstring>
    using namespace std;
    #define endl '
    '
    const int N = 220;
    char g[N][N];
    int dx[4] = {0,0,1,-1},dy[4] = {1,-1,0,0};
    int n,m,sx,sy,gx,gy,mini = INT_MAX;
    bool vis[N][N];
    struct node {
        int x,y,t;
        friend bool operator < (const node a,const node b){
            return a.t > b.t;
        }
    };
    void bfs() {
        priority_queue<node> q;
        q.push({sx,sy,0});
        vis[sx][sy] = 1;
        while(q.size()) {
            node t = q.top();
            if(g[t.x][t.y] == 'r') {
                mini = t.t;
                return ;
            }
            q.pop();
            for(int i = 0;i < 4; ++i) {
                int nx = t.x + dx[i];
                int ny = t.y + dy[i];
                if(g[nx][ny] != '#' && nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny]) {
                    if(g[nx][ny] == '.' || g[nx][ny] == 'r') q.push({nx,ny,t.t + 1});
                    else  q.push({nx,ny,t.t + 2});
                    vis[nx][ny] = 1;
                }
            }
        }
    }
    int main() {
        ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
        while(cin >> n >> m) {
            memset(g,0,sizeof g);
            memset(vis,0,sizeof vis);
            mini = INT_MAX;
            for(int i = 0;i < n; ++i) {
                for(int j = 0;j < m; ++j) {
                    cin >> g[i][j];
                    if(g[i][j] == 'a') sx = i,sy = j;
                }
            }
            bfs();
            if(mini != INT_MAX) cout << mini;
            else cout << "Poor ANGEL has to stay in the prison all his life.";
            cout << endl;
        }
        return 0;
    }
    
        friend bool operator < (const node a,const node b){//重载小于号
            return a.t > b.t;
            //如果 a.t > b.t 返回真,表明要进行交换,否则返回假,不交换。
        }
    
  • 相关阅读:
    python-day24(模块语法)
    python-day23(正则表达式,RE)
    python-day22(序列化)
    python-day21(模块初级)
    python-day20(继承)
    python-day19(约束和异常处理)
    python-day18(反射)
    延迟任务
    亚马逊服务器创建root用户
    sqlalchemy orm
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/12420865.html
Copyright © 2020-2023  润新知