首页 > 代码库 > hdu 4496 D-City (逆向思维的并查集)

hdu 4496 D-City (逆向思维的并查集)

D-City

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 1388    Accepted Submission(s): 520


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
 

 

 

 

        题意:给你n个地点,每2个点之间都有一条路,输入m组数据,就是你要去摧毁的路,问连通分量。

 

        解题思路:删除一条边等于加上了m-1条边,删除2条则相当于加上m-2条边,反过来,我们从后面往前加就好了,将输入的数据反一下。

 

贴出代码:

 

#include <stdio.h>int father[10005];int x[100005], y[100005], num[100005];void MakeSet(int  n){    for(int i = 0; i<n; i++)        father[i] = i;}int FindSet(int x){    if(x != father[x])    {        father[x] = FindSet(father[x]);    }    return father[x];}int main(){    int n, m, a, b;    while(scanf("%d%d", &n, &m)!=EOF)    {        for(int i = 0; i<m; i++)        {            scanf("%d%d", &x[i], &y[i]);        }                MakeSet(n);                num[m-1] = n;        for(int i = m-1; i>0; i--)        {            a = FindSet(x[i]);            b = FindSet(y[i]);            if(a != b)            {                father[a] = b;                num[i-1] = num[i]-1;            }            else                num[i-1] = num[i];        }        for(int i = 0; i<m; i++)            printf("%d\n", num[i]);    }    return 0;}