1015: [JSOI2008]星球大战starwar
很久以前,在一个遥远的星系,一个黑暗的帝国靠着它的超级武器统治者整个星系。某一天,凭着一个偶然的机遇,一支反抗军摧毁了帝国的超级武器,并攻下了星系中几乎所有的星球。这些星球通过特殊的以太隧道互相直 接或间接地连接。但好景不长,很快帝国又重新造出了他的超级武器。凭借这超级武器的力量,帝国开始有计划地摧毁反抗军占领的星球。由于星球的不断被摧毁,两个星球之间的通讯通道也开始不可靠起来。现在,反抗军首领交给你一个任务:给出原来两个星球之间的以太隧道连通情况以及帝国打击的星球顺序,以尽量快的速度求出每一次打击之后反抗军占据的星球的连通快的个数。(如果两个星球可以通过现存的以太通道直接或间接地连通,则 这两个星球在同一个连通块中)。
Input
输入文件第一行包含两个整数,N (1 < = N < = 2M) 和M (1 < = M < = 200,000),分别表示星球的 数目和以太隧道的数目。星球用 0 ~ N-1的整数编号。接下来的M行,每行包括两个整数X, Y,其中(0 < = X <> Y 表示星球x和星球y之间有“以太”隧道,可以直接通讯。接下来的一行为一个整数k,表示将遭受攻击的星球的数目。接下来的k行,每行有一个整数,按照顺序列出了帝国军的攻击目标。这k个数互不相同,且都在0到n-1的范 围内。
Output
输出文件的第一行是开始时星球的连通块个数。接下来的N行,每行一个整数,表示经过该次打击后现存星球 的连通块个数。
Sample Input
8 13
0 1
1 6
6 5
5 0
0 6
1 2
2 3
3 4
4 5
7 1
7 2
7 6
3 6
5
1
6
3
57 Sample Output
1
1
1
2
3
3
最开始想到的是十分暴力的…每次求一遍割顶….
好吧,联通快可以用并查集,但是,并查集只有合并操作,而题目是要求摧毁通道,这正好与合并操作相反,那么就由此想到了将整个过程逆过来,从最后所有要被摧毁的通道全被摧毁,之后每次加进一个通道,用并查集判断是否有多个联通块联通。
附代码
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#define N 400010
#define M 200010
using namespace std;
struct edge {
int to, next;
edge(void) {}
edge(int t, int n):to(t), next(n) {}
}G[M * 2];
int n, m, cnt = 0, k, x, y, num;
int ans[N], f[N], query[N], head[N];
bool can[N];
inline char get_char(void) {
static char buf[100000], *p1 = buf, *p2 = buf;
if (p1 == p2) {
p2 = (p1 = buf) + fread(buf, 1, 100000, stdin);
if (p1 == p2) return EOF;
}
return *p1++;
}
inline void read(int &x) {
x = 0; char c;
for(c = get_char(); c < '0' || c > '9'; c = get_char());
for(; c >= '0' && c <= '9'; x = x * 10 + c - '0', c = get_char());
}
inline int getfa(int x) {
return x == f[x] ? x : f[x] = getfa(f[x]);
}
inline void add_edge(int from, int to) {
G[cnt] = edge(to, head[from]);
head[from] = cnt++;
G[cnt] = edge(from, head[to]);
head[to] = cnt++;
}
int main(void) {
memset(can, 1, sizeof(can));
memset(head, -1, sizeof(head));
read(n); read(m);
for(int i = 0; i < m; i++) {
read(x); read(y);
add_edge(x, y);
}
for(int i = 0; i < n; f[i] = i, i++);
read(k); cnt = 0;
for(int i = 0; i < k; i++) {
read(query[i]); can[query[i]] = 0;
}
int fx, fy; num = n - k;
for(int i = 0; i < n; i++) {
if (!can[i]) continue;
fx = getfa(i);
for(int j = head[i]; j != -1; j = G[j].next) {
if (!can[G[j].to]) continue;
fy = getfa(G[j].to);
if (fx != fy) {
f[fy] = fx; num--;//这里很重要,因为如果f[fx] = fy那么如果多个联通块联通不能够判断出来
}
}
}
ans[cnt++] = num;
for(int i = k - 1; i >= 0; i--) {
int x = query[i]; num++; can[x] = 1;
fx = getfa(x);
for(int j = head[x]; j != -1; j = G[j].next) {
if (!can[G[j].to]) continue;
fy = getfa(G[j].to);
if (fx != fy) {
f[fy] = fx; num--;//这里很重要,因为如果f[fx] = fy那么如果多个联通块联通不能够判断出来
}
}
ans[cnt++] = num;
}
for(int i = cnt - 1; i >= 0; i--) printf("%d\n", ans[i]);
return 0;
}