53952023-05-09 14:12:07mraronLabirintuscpp17Accepted 100/100439ms43344 KiB
#include "labirintus.h"
#include <algorithm>

using namespace std;

int M, R, C;
vector<vector<int>> labyrinth;
vector<int> sz, par;
vector<pair<int,int>> hist;

int find_par(int x) {
    return x==par[x] ? x : find_par(par[x]);
}

void unite(int r1, int c1, int r2, int c2, bool save=false) {
    int x = r1*C+c1, y;
    if (r2<0 || r2>=R) y = (r2==R ? M-2 : M-1);
    else if (c2<0 || c2>=C) y = (c2==C ? M-1 : M-2);
    else y = r2*C+c2;

    x = find_par(x), y = find_par(y);
    if (x==y) return;
    if (sz[x] < sz[y]) swap(x,y);
    sz[x] += sz[y];
    par[y] = x;
    if (save) hist.push_back({x, y});
}

void init_labyrinth(int _R, int _C, std::vector<std::vector<int>> L) {
    R = _R, C = _C;
    labyrinth = L;
    M = R*C+2;
    sz.assign(M, 1), par.resize(M);
    for (int i=0; i<M; ++i) par[i] = i;
    for (int i=0; i<R; ++i) {
        for (int j=0; j<C; ++j) {
            if (labyrinth[i][j] == 0) continue;
            for (int x=i-1; x<=i+1; ++x)
                for (int y=j-1; y<=j+1; ++y)
                    if (x<0 || x>=R || y<0 || y>=C || labyrinth[x][y] == 1)
                        unite(i,j, x,y);
        }
    }
}

bool can_escape(int N, std::vector<int> U, std::vector<int> V) {
    hist.clear();
    for (int k=0; k<N; ++k) {
        int i = U[k], j = V[k];
        for (int x=i-1; x<=i+1; ++x)
            for (int y=j-1; y<=j+1; ++y)
                if (x<0 || x>=R || y<0 || y>=C || labyrinth[x][y] == 1) 
                    unite(i,j, x,y, true);
        labyrinth[i][j] = 1;
    }
    bool ans = (find_par(M-2) != find_par(M-1));
    reverse(hist.begin(), hist.end());
    for (auto [x,y] : hist) {
        par[y] = y;
        sz[x] -= sz[y];
    }
    for (int k=0; k<N; ++k) {
        labyrinth[U[k]][V[k]] = 0;
    }

    return ans;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1328 KiB
2Accepted178ms40500 KiB
subtask215/15
3Accepted32ms3180 KiB
4Accepted8ms3396 KiB
5Accepted115ms2892 KiB
6Accepted115ms2608 KiB
7Accepted81ms3800 KiB
8Accepted82ms4164 KiB
subtask318/18
9Accepted209ms3684 KiB
10Accepted182ms3084 KiB
11Accepted416ms41684 KiB
12Accepted402ms42024 KiB
13Accepted398ms41976 KiB
14Accepted439ms42076 KiB
subtask428/28
15Accepted257ms42412 KiB
16Accepted259ms42632 KiB
17Accepted263ms42576 KiB
18Accepted150ms42704 KiB
19Accepted252ms42636 KiB
20Accepted120ms42592 KiB
21Accepted122ms42920 KiB
22Accepted250ms42604 KiB
23Accepted246ms42864 KiB
subtask539/39
24Accepted35ms3960 KiB
25Accepted17ms3868 KiB
26Accepted115ms4420 KiB
27Accepted115ms3960 KiB
28Accepted115ms4184 KiB
29Accepted115ms3968 KiB
30Accepted432ms42984 KiB
31Accepted402ms43036 KiB
32Accepted275ms43032 KiB
33Accepted405ms43236 KiB
34Accepted229ms43316 KiB
35Accepted228ms43276 KiB
36Accepted310ms43180 KiB
37Accepted287ms43180 KiB
38Accepted294ms43244 KiB
39Accepted289ms43344 KiB