WA #9 || 并查集做法 || 萌新求助

P1197 [JSOI2008] 星球大战

Furthe77oad @ 2023-03-14 22:31:23

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int cnt;
int nxt[maxn << 1], hed[maxn << 1], ver[maxn << 1], pre[maxn << 1];
void adde(int u, int v) {
    cnt++;
    pre[cnt] = u;
    ver[cnt] = v;
    nxt[cnt] = hed[u];
    hed[u] = cnt;
    return;
}
int f[maxn];
int find(int x) {
    return x == f[x] ? x : f[x] = find(f[x]);
}
int n, m, k;
int od[maxn], bo[maxn];
int ans[maxn];
signed main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) f[i] = i;
    for (int i = 1; i <= m; i++) {
        int u, v;
        scanf("%d%d", &u, &v);
        adde(u, v);
        adde(v, u);
    }
    scanf("%d", &k);
    for (int i = 1; i <= k; i++) {
        scanf("%d", &od[i]);
        bo[od[i]] = 1;
    }
    int tot = n - k;
    for (int i = 1; i <= m << 1; i++) { //???
        int u = pre[i];
        int v = ver[i];
        if (bo[u] == 0 && bo[v] == 0) {
            if (f[find(u)] != f[find(v)]) {
                tot--;
                f[find(u)] = f[find(v)];
            }
        }
    }
    ans[k + 1] = tot;
    for (int i = k; i >= 1; i--) {
        int u = od[i];
        tot++;
        bo[u] = 0;
        for (int j = hed[u]; j; j = nxt[j]) {
            int v = ver[j];
            if (bo[v] == 0 && f[find(u)] != f[find(v)]) {
                tot--;
                f[find(u)] = f[find(v)];
            }
        }
        ans[i] = tot;
    }
    for (int i = 1; i <= k + 1; i++) {
        printf("%d\n", ans[i]);
    }
    return 0;
}

rt,求解

WA #9 记录


by Hugo_Peng @ 2023-03-14 22:39:01

@Furthe77oad n \le 2m


by Konjac_16 @ 2023-03-15 07:35:06

数组开小了,要开 4e5


|