网上说用并查集,半天没看懂,我的代码题中的测试数据通过,但没通过别人给的测试数据
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class t1182 {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int K = scanner.nextInt();
int count = 0;
Map<Integer, Set<Integer>> eatMap = new HashMap<Integer, Set<Integer>>();
List<Set<Integer>> groupList = new ArrayList<Set<Integer>>();
for (int i = 0; i < K; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
if (b > N || c > N) {
count++;
continue;
}
// 如果1,判断是否吃或被吃
if (a == 1) {
if (b == c) {
continue;
}
Set<Integer> eat1 = eatMap.get(b);
if (null != eat1 && eat1.contains(c)) {
count++;
} else {
Set<Integer> eat2 = eatMap.get(c);
if (null != eat2 && eat2.contains(b)) {
count++;
}
// 增加同类关系
else {
Set<Integer> group = null;
for (Set<Integer> g : groupList) {
if (g.contains(b) || g.contains(c)) {
group = g;
break;
}
}
if (null == group) {
group = new HashSet<Integer>();
groupList.add(group);
}
group.add(b);
group.add(c);
}
}
}
// 如果2,判断是否同类、是否被吃
else {
if (b == c) {
count++;
continue;
}
boolean isGroup = false;
for (Set<Integer> g : groupList) {
if (g.contains(b) && g.contains(c)) {
isGroup = true;
break;
}
}
// 判断是否同类
if (isGroup) {
count++;
} else {
// 判断是否被吃
Set<Integer> eat = eatMap.get(c);
if (null != eat && eat.contains(b)) {
count++;
}
// 增加吃的关系
else {
Set<Integer> eatR = eatMap.get(b);
if (null == eatR) {
eatR = new HashSet<Integer>();
eatMap.put(b, eatR);
}
eatR.add(c);
}
}
}
}
scanner.close();
System.out.println(count);
}
}