// 样本进来会包一层,叫做元素 publicstaticclassElement<V> { public V value;
publicElement(V value){ this.value = value; } }
publicstaticclassUnionFindSet<V> {
public HashMap<V, Element<V>> elementMap; // key 某个元素value 该元素的父 public HashMap<Element<V>, Element<V>> fatherMap; // key 某个集合的代表元素, value该集合的大小 public HashMap<Element<V>, Integer> sizeMap;
publicUnionFindSet(List<V> list){ elementMap = new HashMap<>(); fatherMap = new HashMap<>(); sizeMap = new HashMap<>();
for (V value : list) { Element element = new Element(value); elementMap.put(value, element); fatherMap.put(element, element); sizeMap.put(element, 1); } }
// 给定一个element,网上找,把代表元素返回 private Element<V> findHead(Element<V> element){ Stack<Element<V>> path = new Stack<>(); while (element != fatherMap.get(element)) { path.push(element); element = fatherMap.get(element); } while (!path.isEmpty()) { // 路径铺平 fatherMap.put(path.pop(), element); } return element; }
publicbooleanisSameSet(V a, V b){ if (elementMap.containsKey(a) && elementMap.containsKey(b)) { return findHead(elementMap.get(a)) == findHead(elementMap.get(b)); } returnfalse; }
publicvoidunion(V a, V b){ if (elementMap.containsKey(a) && elementMap.containsKey(b)) { Element<V> aF = findHead(elementMap.get(a)); Element<V> bF = findHead(elementMap.get(b)); if (aF != bF) { Element<V> big = sizeMap.get(aF) >= sizeMap.get(bF) ? aF : bF; Element<V> small = big == aF ? bF : aF; fatherMap.put(small, big); sizeMap.put(big, sizeMap.get(aF) + sizeMap.get(bF)); sizeMap.remove(small); } } }
publicstaticvoidmain(String[] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); // 人数 int m = scanner.nextInt(); // 关系数 int p = scanner.nextInt(); // 询问多少个关系
List<Integer> personList = new ArrayList<>(); int[][] relation = newint[m][2]; for (int i = 0; i < m; i++) { int p1 = scanner.nextInt(); int p2 = scanner.nextInt(); if (!personList.contains(p1)) personList.add(p1); if (!personList.contains(p2)) personList.add(p2); relation[i][0] = p1; relation[i][1] = p2; // relationMap.put(p2, p1); }
UnionFindSet<Integer> unionSet = new UnionFindSet<>(personList);
for (int i = 0; i < m; i++) { unionSet.union(relation[i][0], relation[i][1]); }
for (int i = 0; i < p; i++) { int p1 = scanner.nextInt(); int p2 = scanner.nextInt(); if (unionSet.isSameSet(p1, p2)) { System.out.println("Yes"); } else { System.out.println("No"); } } }