题解 | #wyh的吃鸡#

wyh的吃鸡

https://ac.nowcoder.com/acm/problem/15445

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

struct q {
    int x, y;
    int dis;
    bool car;

    bool operator < (const q &s) const {
        if(dis == s.dis) return car < s.car;
        return dis > s.dis;
    }
};

int n, k;
int sx, sy;

char g[110][110];
int st[110][110][2];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
priority_queue <q> qu;

int bfs() {
    memset(st, 0, sizeof st);
    qu.push({sx, sy, 0, false}), st[sx][sy][0] = 1;

    while(qu.size()) {
        int x = qu.top().x, y = qu.top().y, now = qu.top().dis, flag = qu.top().car;

        for(int i = 0; i < 4; i++) {
            int tx = x + dx[i], ty = y + dy[i];

            if(st[tx][ty][flag] == 1 || tx < 1 || tx > n || ty < 1 || ty > n || g[tx][ty] == 'O') continue;

            if(g[tx][ty] == 'X' && flag) return now + 1;
            if(g[tx][ty] == 'X' && !flag) return now + 2;

            st[tx][ty][flag] = 1;
            if(g[tx][ty] == 'C' && !flag) qu.push({tx, ty, now + 2, true});
            if(g[tx][ty] == 'C' && flag) qu.push({tx, ty, now + 1, true});

            if(g[tx][ty] == '.' && flag) qu.push({tx, ty, now + 1, true});
            if(g[tx][ty] == '.' && !flag) qu.push({tx, ty, now + 2, false});
        }

        qu.pop();
    }

    return -1;
}

int main() {
    int t;
    cin >> t;

    while(t --) {
        cin >> n >> k;

        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++) {
                cin >> g[i][j];
                if(g[i][j] == 'S') sx = i, sy = j;
            }

        while(qu.size()) qu.pop();

        int ans = bfs();
        //cout << ans << endl;

        if(ans != -1 && ans <= k) cout << "YES" << endl << ans << endl;
        else cout << "NO" << endl;
    }

    return 0;
}


本题使用bfs + 优先队列解决
注意: (1) 当dis'相同时优先让有car的点走 (2) 有car与无car的st应分别记录
全部评论

相关推荐

认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务