HDU 4496D-City2013通化邀請賽D題(並查集 需要壓縮路徑)

果7發表於2013-08-24

D-City

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


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
Hint
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.
 

Source
 


                    題目大意:給你n個頂點,m條邊。每次會摧毀一條邊,到最後把m條邊都摧毀完。問你每次摧毀的時候還有幾個集合。

            解題思路:邊會逐漸摧毀,我們關心的是點上還連著多少邊。摧毀1條邊還有m-1條邊,摧毀2條邊還有m-2條邊。我們可以直接使用並查集處理,從後往前處理,依次加上第m條邊,第m-1條邊。這樣處理即可。不過需要在找father的時候壓縮路徑,不然會TLE詳見程式碼。

            題目地址:D-City

AC程式碼:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=100005;
int a[maxn],b[maxn],father[maxn],res[maxn],n,cnt;

void init()
{
    int i;
    for(i=0;i<n;i++)
        father[i]=i;
}

int find1(int x)  //路徑壓縮的find1
{
    if(father[x]!=x)
    father[x]=find1(father[x]);
    return father[x];
}

/*int find1(int x)  //不壓縮路徑會TlE
{
   int r=x;
   while(father[r]!=r)
       r=father[r];
   return r;
}*/

void merge1(int p1,int p2)
{
    int s1=find1(p1);
    int s2=find1(p2);
    if(s1!=s2) cnt--;  //若有合併的集合就減少
    father[s1]=s2;
}

int main()
{
    int m,i;
    while(~scanf("%d%d",&n,&m))
    {
        init();
        cnt=n;
        for(i=0;i<m;i++)
            scanf("%d%d",&a[i],&b[i]);
        res[m]=cnt;
        for(i=m-1;i>=1;i--)  //逆序加邊
        {
            merge1(a[i],b[i]);
            res[i]=cnt;
        }

        for(i=1;i<=m;i++)
            printf("%d\n",res[i]);
    }
    return 0;
}


相關文章