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
并查集模板题
#include <iostream>
#include <cmath>
#include <math.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
int fa[1000005];
int num[1000005];
int n, m;
void init()
{
for (int i = 0; i < n; i++)
{
fa[i] = i;
num[i] = 1;
}
return;
}
int find(int x)
{
if (fa[x] == x)
return x;
return fa[x] = find(fa[x]);
}
void join(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
{
fa[fx] = fy;
num[fy] += num[fx];
}
return;
}
int main()
{
while (cin >> n >> m)
{
int a, b;
init();
for (int i = 0; i < m; i++)
{
cin >> a >> b;
join(a, b);
}
sort(num, num + n + 1);
cout << num[n] << endl;
}
return 0;
}