Luxer is a really bad guy. He destroys everything he met.
One day Luxer went to D-city. D-city has N D-points and M D-lines. Each D-line connects exactly two D-points. Luxer will destroy all the D-lines. The mayor of D-city wants to know how many connected blocks of D-city left after Luxer destroying the first K D-lines in the input.
Two points are in the same connected blocks if and only if they connect to each other directly or indirectly.
One day Luxer went to D-city. D-city has N D-points and M D-lines. Each D-line connects exactly two D-points. Luxer will destroy all the D-lines. The mayor of D-city wants to know how many connected blocks of D-city left after Luxer destroying the first K D-lines in the input.
Two points are in the same connected blocks if and only if they connect to each other directly or indirectly.
Then following M lines each containing 2 space-separated integers u and v, which denotes an D-line.
Constraints:
0 < N <= 10000
0 < M <= 100000
0 <= u, v < N.
5 10 0 1 1 2 1 3 1 4 0 2 2 3 0 4 0 3 3 4 2 4
1
1
1
2
2
2
2
3
4
5
The graph given in sample input is a complete graph, that each pair of vertex has an edge connecting them, so there's only 1 connected block at first. The first 3 lines of output are 1s because after deleting the first 3 edges of the graph, all vertexes still connected together. But after deleting the first 4 edges of the graph, vertex 1 will be disconnected with other vertex, and it became an independent connected block. Continue deleting edges the disconnected blocks increased and finally it will became the number of vertex, so the last output should always be N.
题意:给出n个点,m条边,然后输入m条边,最后按照顺序删除边,求每次删除一条边的时候图的连通分量数。下面解释样例一:
依次输入:
5 10
0 1
1 2
1 3
1 4
0 2
2 3
0 4
0 3
3 4
2 4,得到的图如下:
连通分量为1
删除0 1 这条边:
连通分量为1
删除 1 2 这条边:
连通分量为1
删除 1 3 这条边:
连通分量为1
依次 1 4 这条边:
连通分量为2
连通分量为2
为2
为2
为3
为4
为5
这样就很明确了,我们可以倒序,每次连接边,求集合的数量即可:
#include <stdio.h>
#include <string.h>
int f[10005];
int a[100005];
struct node{
int x, y;
}s[100005];
int getf(int v) {
if(f[v] != v) {
f[v] = getf(f[v]);
}
return f[v];
}
void init(int n) {
for(int i = 0; i <= n; i++) {//从0开始,这点要注意
f[i] = i;
a[i] = 0;
}
}
int main() {
int n, m;
while(~scanf("%d %d", &n, &m)) {
init(n);
for(int i = 1; i <= m; i++) {
scanf("%d %d", &s[i].x, &s[i].y);
}
a[m] = n;
for(int i = m; i >= 1; i--) {
int t1 = getf(s[i].x);
int t2 = getf(s[i].y);
if(t1 != t2) {
f[t1] = t2;
a[i-1] = a[i]-1;
}
else a[i-1] = a[i];
}
for(int i = 1; i <= m; i++) {
printf("%d\n", a[i]);
}
}
return 0;
}