典型的并查集的题目
题目:n个人,如果A和B认识,B和C认识,那么A和C就认识,求最大的朋友集合中的人数
换句话说,就是求最大的连通分量
代码如下:
#include <cstdio>
const int N = 30005;
int fa[N], ans[N], n, m, T;
int find( int x ) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int main()
{
scanf("%d", &T);
while ( T-- ) {
scanf("%d%d", &n, &m);
for ( int i = 1; i <= n; ++i ) fa[i] = i, ans[i] = 0;
for ( int i = 0; i < m; ++i ) {
int x, y, u, v;
scanf("%d%d", &u, &v);
x = find(u);
y = find(v);
if ( x != y )
fa[x] = y;
}
for ( int i = 1; i <= n; ++i )
ans[find(i)]++;
int a = 0;
for ( int i = 1; i <= n; ++i )
if ( a < ans[i] ) a = ans[i];
printf("%d\n", a);
}
return 0;
}