https://www.nowcoder.com/practice/11ee0516a988421abf40b315a2b28d08
描述
现在有107个用户,编号为1- 107,现在已知有m对关系,每一对关系给你两个数x和y,代表编号为x的用户和编号为y的用户是在一个圈子中,例如:A和B在一个圈子中,B和C在一个圈子中,那么A,B,C就在一个圈子中。现在想知道最多的一个圈子内有多少个用户。
输入描述:
第一行输入一个整数T,接下来有T组测试数据。
对于每一组测试数据:第一行输入1个整数n,代表有n对关系。
接下来n行,每一行输入两个数x和y,代表编号为x和编号为y的用户在同一个圈子里。
1 ≤ T ≤ 10
1 ≤ n ≤ 105
1 ≤ x, y ≤ 107
输出描述:
对于每组数据,输出一个答案代表一个圈子内的最多人数
示例1
输入:
2 4 1 2 3 4 5 6 1 6 4 1 2 3 4 5 6 7 8
输出:
4 2
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
/*
*
* 并查集
*/
public class Main {
static int[] root = new int[10000001];//用于判断连通分量,root[x]表示点x属于哪一个连通分量(用根节点表示一个连通分量,最开始每个点都看作一个连通分量)。
static int[] nums = new int[10000001];//分量中的节点数
static int find(int x) {//寻找x所处连通分量的根
//这里路径压缩, 不希望长长了链查询(只要我们在查询的过程中,把沿途的每个节点的父节点都设为根节点即可。下一次再查询时,我们就可以省很多事)
return root[x]==x ? x : (root[x] = find(root[x]));//注意赋值运算符=的优先级没有三元运算符?:高,这里要加括号。
}
public static void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if(rootX!=rootY) {//不在同一个连通分量中
//把rootY所表示的连通分量和rootX所表示的连通分量合并(rootY加入rootX)
//rootY的根是rootX (y的根节点的根是rootX, x的根节点也是rootX, 所以现在x,y在一个连通分量中)
root[rootY] = rootX;
nums[rootX] += nums[rootY];//节点数和合并
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0) {
for(int i=0; i<root.length; i++) {//初始化每个点的根节点都是本身
root[i] = i;
nums[i] = 1;
}
int n = in.nextInt();
for(int i=0; i<n; i++) {
int x = in.nextInt();
int y = in.nextInt();
union(x, y);
}
//将最大的连通分量挑出来
int max = 0;
for(int i=0; i<nums.length; i++) {
if(nums[i]>max) max = nums[i];
}
System.out.println(max);
}
}
}