P3956 [NOIP 2017 普及组] 棋盘代码

· · 题解

#include <iostream> 
#include <deque>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 110;
int n, m, a[N][N], d[N][N][2];
bool vis[N][N][2];
int fx[4] = {0, 0, 1, -1};
int fy[4] = {1, -1, 0, 0};

struct node { int x, y; bool c; int w; };
deque<node> q1, q2; int D;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= n; ++i) 
        for (int j = 1; j <= n; ++j) a[i][j] = -1;

    for (int i = 1; i <= m; ++i) {
        int x, y; 
        cin >> x >> y;
        cin >> a[x][y];
    } 

    memset(d, 0x3f, sizeof d);

    d[1][1][a[1][1]] = 0, D = 0;
    q1.push_front({1, 1, (bool)a[1][1], 0});

    while (!q1.empty() || !q2.empty()) {
        if (q1.empty()) swap(q1, q2);
        auto u = q1.front(); q1.pop_front();
        if (u.x == n && u.y == n) {
            cout << u.w << '\n';
            return 0;
        }
        if (u.w > D) {
            D = u.w;
            while (!q2.empty() && q2.front().w == D + 1)
                q1.push_back(q2.front()), q2.pop_front();
        }
        if (vis[u.x][u.y][u.c]) continue;
        vis[u.x][u.y][u.c] = 1;

        for (int i = 0; i < 4; ++i) {
            int x = u.x + fx[i], y = u.y + fy[i];
            if (x <= 0 || y <= 0 || x > n || y > n) continue;

            if (a[x][y] != -1) {
                if (u.c == a[x][y]) {
                    if (u.w < d[x][y][a[x][y]]) 
                        d[x][y][a[x][y]] = u.w, q1.push_front({x, y, (bool)a[x][y], u.w});
                } else {
                    if (u.w + 1 < d[x][y][a[x][y]])
                        d[x][y][a[x][y]] = u.w + 1, q1.push_back({x, y, (bool)a[x][y], u.w + 1});
                } 
            } else {
                if (a[u.x][u.y] == -1) continue;
                if (u.w + 2 < d[x][y][u.c])
                    d[x][y][u.c] = u.w + 2, q2.push_front({x, y, u.c, u.w + 2});
                if (u.w + 3 < d[x][y][!u.c])
                    d[x][y][!u.c] = u.w + 3, q2.push_back({x, y, !u.c, u.w + 3});
            }
        }
    }

    cout << -1 << '\n';
    return 0;
}