题目描述
幼儿园老师安排小朋友做游戏,现在需要给N个小朋友进行分组,老师让每个同学写一个名字,代表这位小朋友想和谁分到一组,请问老师在满足所有小朋友意愿的情况下,最多可以将班级分成多少组?
输入描述:
第一行输入N,0<N<100000
接下来是N行代表每个小朋友希望和谁分到一组,如“John Jack”,代表John希望和Jack分到一组,两个名字之间以空格分隔,名字本身不存在空格。
输出描述:
分组的最多数量
示例1
输入
6
Jack Tom
Alice John
Jessica Leonie
Tom Alice
John Jack
Leonie Jessica
输出
2
示例2
输入
3
Xiaoming Xiaohong
Xiaohong Xiaoqiang
Xiaoqiang Xiaoming
输出
1
以下是其他人写的代码,用两个集合来判断还不太明白(并查集?以后学完再回来看)
import java.util.*;
/**
* @author
* @create 2021-04-08 22:03
*/
public class Solution0407_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
int n = scan.nextInt();
scan.nextLine();
Map<String, String> map = new HashMap<>();
String[][] arr = new String[n][2];
for (int i = 0; i < n; i++) {
String s = scan.nextLine();
String[] relation = s.split(" ");
map.put(relation[0],relation[1]);
arr[i][0] = relation[0];
arr[i][1] = relation[1];
}
/*
Jack Tom
Alice John
Jessica Leonie
Tom Alice
John Jack
Leonie Jessica
*/
HashSet<String> set = new HashSet<>();
int res = 0;
for (int i = 0; i < n; i++) {
if (!set.contains(arr[i][0])){
HashSet<String> hash = new HashSet<>();
String temp = arr[i][0];
while (!set.contains(temp) && !hash.contains(temp)){
set.add(temp);
hash.add(temp);
temp = map.get(temp);
}
if (set.contains(temp) && !hash.contains(temp)){
continue;
}
res++;
}
}
System.out.println(res);
}
}
}
简化版本也可以通过测试样例1,2,其他不知道
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
/**
* @author
* @create 2021-04-08 23:31
*/
public class Solution0407_1simple {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = scan.nextInt();
scan.nextLine();
Map<String, String> map = new HashMap<>();
String[] arr = new String[n];//只保存第一个同学
for (int i = 0; i < n; i++) {
String s = scan.nextLine();
String[] relation = s.split(" ");
map.put(relation[0], relation[1]);
arr[i] = relation[0];//只保存第一个同学
}
HashSet<String> set = new HashSet<>();
int res = 0;
for (int i = 0; i < n; i++) {
if (!set.contains(arr[i])){
String temp = arr[i];
while (!set.contains(temp)){
set.add(temp);
temp = map.get(temp);
}
res++;
}
}
System.out.println(res);
}
}
}