1. 程式人生 > >More is better(並查集)

More is better(並查集)

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)

當N為0時輸入結束。
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

這道題是一個並查集的題目,只不過不是問有多少個集合,而是找集合中的元素個數,只需要合併的時候將合併的子節點數目加到父節點上就好了。

#include<bits/stdc++.h>
#define fi first
#define se second
#define FOR(a) for(int i=0;i<a;i++)
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
using namespace std;

int f[10000005],vis[10000005];



int fid(int x)
{
	if(f[x]==x) return x;
	else return f[x]=fid(f[x]);
}

void joint(int x,int y)
{
	int fx=fid(x);
	int fy=fid(y);
	if(fx!=fy)
	{
		f[fx]=fy;
		vis[fy]+=vis[fx];//將子節點上的數目加到父節點上
	}
}
int main()
{
	int n,m,x,y,t;
	while(scanf("%d",&n)!=EOF)

	{


		int sum=1,t=1,flag=0;
		int cnt=0,x,y;

		for(int i=1;i<=10000005;i++) f[i]=i;
		for(int i=1;i<=10000005;i++) vis[i]=1;// 初始為每個都為1
		for(int i=0;i<n;i++)
		{
			scanf("%d%d",&x,&y);

			//show2(fid(x),fid(y));
			t=max(x,t);
			t=max(y,t);
			joint(x,y);

		}
		//cout<<t<<endl;

		for(int i=1;i<=t;i++)
		{

			cnt=max(cnt,vis[i]);

		}
		printf("%d\n",cnt);



	}
}