一看到这种求连通关系的就要想到使用并查集!
腾讯例题:
现在有10000000个用户,编号为1- 10000000,现在已知有m对关系,每一对关系给你两个数x和y,代表编号为x的用户和编号为y的用户是在一个圈子中,例如:A和B在一个圈子中,B和C在一个圈子中,那么A,B,C就在一个圈子中。现在想知道最多的一个圈子内有多少个用户。
解答:
import java.util.*;
import java.util.Scanner;
class UnionFind{
public static int[] people = new int[10000001]; //编号从1开始
public static int[] numFriends = new int[10000001];
public UnionFind(){
for(int i = 0; i < 10000001; i++){
people[i] = i;
numFriends[i] = 1;
}
}
public int find(int x){
while(x != people[x]){
people[x] = people[people[x]];
x = people[x];
}
return x;
}
public void union(int x, int y){
int x_people = find(x);
int y_people = find(y);
people[x_people] = y_people;
if(x_people == y_people) return;
numFriends[x_people] += numFriends[y_people];
numFriends[y_people] = numFriends[x_people];
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int numTest = sc.nextInt();
for(int i = 0; i < numTest; i++){
int numRelation = sc.nextInt();
UnionFind uf = new UnionFind();
for(int j = 0; j < numRelation; j++){
int x = sc.nextInt();
int y = sc.nextInt();
uf.union(x, y);
}
int res = 0;
for(int k = 0; k < 10000001; k++){
res = Math.max(res, uf.numFriends[k]);
}
System.out.println(res);
}
}
}