星球大战
分析
离线+
倒序处理。
实现
#include <iostream>
#include <cstring>
using namespace std;
const int N = 800010;
struct edge {
int to, next;
};
edge e[2 * 2 * N];
int idx, head[N];
int n, m, k;
int a[N];
bool mark[N];
int f[N];
int res[N];
void add_edge (int u, int v) {
e[idx].to = v;
e[idx].next = head[u];
head[u] = idx ++;
}
int find (int x) {
if (f[x] == x) return x;
return f[x] = find(f[x]);
}
void merge (int x, int y) {
f[find(x)] = find(y);
}
bool query (int x, int y) {
return find(x) == find(y);
}
int main () {
memset(head, -1, sizeof(head));
scanf("%d%d", &n, &m);
for (int i = 1, u, v; i <= m; ++ i) {
scanf("%d%d", &u, &v);
++ u, ++ v;
add_edge(u, v);
add_edge(v, u);
}
scanf("%d", &k);
for (int i = 1; i <= k; ++ i) {
scanf("%d", &a[i]);
mark[++ a[i]] = true; // 摧毁
}
for (int i = 1; i <= n; ++ i) f[i] = i;
int cnt = 0; // 连通块数
for (int i = 1; i <= n; ++ i) {
if (mark[i] == true) continue;
for (int j = head[i]; j != -1; j = e[j].next) {
int to = e[j].to;
if (mark[to] == true) continue;
merge(i, to);
}
}
for (int i = 1; i <= n; ++ i)
cnt += (f[i] == i && mark[i] == false);
for (int i = k; i >= 1; -- i) { // 倒序处理
res[i] = cnt;
mark[a[i]] = false;
++ cnt;
for (int j = head[a[i]]; j != -1; j = e[j].next) {
int to = e[j].to;
if (mark[to] == false && query(a[i], to) == false) {
merge(a[i], to);
-- cnt;
}
}
}
res[0] = cnt;
for (int i = 0; i <= k; ++ i)
printf("%d\n", res[i]);
return 0;
}