朋友(并查集)
题目描述
有一个城镇,住着n个市民。已知一些人互相为朋友。引用一个名人的话说,朋友的朋友也是朋友。意思是说如果A和B是朋友,C和B是朋友,则A和C是朋友.你的任务是数出最大朋友组的人数。
输入
输入第一行由N,M组成,N是市民的个数(1<=n<=30000),m是朋友对的个数(0<=m<=500000)。下面的m行每一行由两个数A和B组成(1<=A,B<=N,A<>B)表示A和B是朋友。注意给的朋友对可能会有重复。
输出
输出仅有一行包含一个整数,表示要求的最大朋友组的人数。
样例输入
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 10
1 2
9 10
8 9
样例输出
6
思路:经典并查集,需要额外开一个计数的数组,记录父节点个数,然后找到最大值,附上AC代码
import java.util.Scanner;
public class Main
{
public static int find(int[] set, int x)
{
if(set[x] == x)
return x;
else
return find(set, set[x]);
}
public static void main(String[] argc)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt(); int m = in.nextInt();
int[] set = new int[30005];
int[] cnt = new int[30005];
for(int i = 1; i <= n; ++i)
{
set[i] = i;
cnt[i] = 1;
}
int res = 0;
while(m-- > 0)
{
int i = in.nextInt(); int j = in.nextInt();
int father_i = find(set, i);
int father_j = find(set, j);
if(father_i != father_j)
{
set[father_j] = father_i;
cnt[father_i] += cnt[father_j];
res = Math.max(res, cnt[father_i]);
}
}
System.out.println(res);
}
}