HDUOJ----More is better(并查集)

More is better

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 327680/102400 K (Java/Others) Total Submission(s): 10473    Accepted Submission(s): 3877

Problem Description
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.
Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
 
Input
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)
 
Output
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
 
Sample Input
4 1 2 3 4 5 6 1 6 4 1 2 3 4 5 6 7 8
 
Sample Output
4 2
Hint
A and B are friends(direct or indirect), B and C are friends(direct or indirect), then A and C are also friends(indirect). In the first sample {1,2,5,6} is the result. In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.
 
Author
lxlcrystal@TJU
 
Source
 
Recommend
lcy
并查集可以解。。。。求的是集合里面元素的个数:即求出最大的秩就行了!
代码:
 1 #include<iostream>

 2 #include<cstdio>

 3 #define maxn 100001

 4 using namespace std;

 5 int father[maxn+5],rank[maxn+5];

 6 void inite(int n)

 7 {

 8     for(int i=1;i<=n;i++)

 9     {

10         father[i]=i;

11         rank[i]=1;

12     }

13 }

14 

15 int findset(int x)

16 {

17    if(x!=father[x])

18    {

19        father[x]=findset(father[x]);

20    }

21   return father[x];

22 }

23 

24 void unset(int x,int y)

25 {

26     x=findset(x);

27     y=findset(y);

28     if(x==y) return ;

29    if(rank[x]>rank[y])

30    {

31        father[y]=father[x];

32        rank[x]+=rank[y];

33    }

34    else

35    {

36        father[x]=father[y];

37        rank[y]+=rank[x];

38    }

39 }

40 

41 int main()

42 {

43     int n,a,b,i,max;

44     while(scanf("%d",&n)!=EOF)

45     {

46         inite(maxn);

47         for(i=0;i<n;i++)

48         {

49             scanf("%d %d",&a,&b);

50             unset(a,b);

51         }

52      for(i=1;i<=maxn;i++)

53      {

54         if(i==1||max<rank[i])

55          max=rank[i];

56      }

57      printf("%d\n",max);

58     }

59   return 0;

60 }
View Code

 

你可能感兴趣的:(more)