CSU 1045: 并查集 带权并查集
Description
大一的学一下,大二以上还不会并查集的统统去面壁。
Input
多组数据,每组第一行两个正整数n,m,表示有1~n这n个编号,m个关系。
接下来m行,每行两个数i, j, 1 <= i, j <= n,表示i和j是一组的。
每个编号自己和自己是一组的。
1 < n < 1000000 ,1 < m < 100000 。
Output
每组数据输出一行,一个数,表示组员最多的组的组员个数。
Sample Input
10 5 1 2 3 5 2 6 4 7 9 6
Sample Output
4
Hint
Source
中南大学2012年暑期集训队选拔赛思路: 带权并查集
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int f[1000005];
int n,m;
int a,b;
int father(int x)
{
if(f[x] <=0 )
return x;
else
return f[x] = father(f[x]);
}
void union_(int a,int b)
{
int root1 = father(a);
int root2 = father(b);
if(root1 == root2)
return;
f[root1] += f[root2];
f[root2] = root1;
}
int main()
{
while(scanf("%d%d",&n,&m) != EOF)
{
memset(f,-1,sizeof(f));
for(int i = 0 ; i < m ; i++)
scanf("%d%d",&a,&b),union_(a,b);
int minx = 0;
for(int i = 1 ; i <= n ; i++)
minx = min(minx,f[i]);
printf("%d\n",-minx);
}
return 0;
}