Problem Description

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.

Input

First line of the input contains two integers N and M.
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.

Output

Output M lines, the ith line is the answer after deleting the first i edges in the input.

Sample Input

5 10 
0 1 
1 2 
1 3 
1 4 
0 2 
2 3 
0 4 
0 3 
3 4 
2 4

Sample Output

1 
1 
1 
2 
2 
2 
2 
3 
4 
5

解题思路

  反向并查集求联通块数;

  逆向思维,假设一开始每个点都不连通的,从给定的边中逆序读入数据,相当于给初始化的图增加边,如果有两个联通分量联通了则现在的连通分量块数等于上一个连通分量的块数 - 1;

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

代码如下

Hdu 4496 D-City 算法 第1张
 1 #include<cstdio>
 2 #include<iostream>
 3 using namespace std;
 4 const int maxn = 100100;
 5 int n, m;
 6 int f[maxn], a[maxn], b[maxn], sum[maxn];
 7 void init(){
 8     for(int i = 0; i < n; i++)    f[i] = i;
 9 }
10 int getf(int v){
11     if(f[v] == v)   return v;
12     else    return f[v] = getf(f[v]);
13 }
14 int main(){
15     while(~scanf("%d %d", &n, &m)){
16         init();
17         for(int i = 1; i <= m; i++){
18             scanf("%d %d", &a[i], &b[i]);
19         }
20         sum[m] = n;
21         for(int i = m; i >= 1; i--){
22             int t1 = getf(a[i]), t2 = getf(b[i]);
23             if(t1 != t2){
24                 f[t2] = t1;
25                 sum[i - 1] = sum[i] - 1;
26             }
27             else{
28                 sum[i - 1] = sum[i];
29             }
30         }
31         for(int i = 1; i <= m; i++){
32             printf("%d\n", sum[i]);
33         }
34     }
35     return 0;
36 }
D-City

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄