解题思路:
注意事项:
参考代码:
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class Main { static Map<Integer, UnionNode.Node> pntAndMap = new HashMap<Integer, UnionNode.Node>(); static Set<UnionNode.Node> nod = new HashSet<UnionNode.Node>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int index = 1; int[][] a =new int[m+1][n+1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { a[i][j] = index++; pntAndMap.put(a[i][j], new UnionNode.Node()); } } int k = sc.nextInt(); for (int i = 0; i < k; i++) { UnionNode.Node s = pntAndMap.get(sc.nextInt()); UnionNode.Node e = pntAndMap.get(sc.nextInt()); if(UnionNode.find(s) != UnionNode.find(e)){ UnionNode.Union(s, e); } } Set<UnionNode.Node> res = new HashSet<>(); for (int i = 1; i < a.length; i++) { for (int j = 1; j < a[i].length; j++) { UnionNode.Node node = pntAndMap.get(a[i][j]); UnionNode.Node f = UnionNode.find(node); res.add(f); } } System.out.println(res.size()); } } class UnionNode{ public static Node find(Node x){ Node p = x; Set<Node> set = new HashSet<>(); while(p.parent != null){ set.add(p); p = p.parent; } for (Node node : set) { node.parent = p; } return p; } public static void Union(Node x, Node y){ find(y).parent = find(x); } static class Node{ public Node parent; } }
0.0分
1 人评分
C语言程序设计教程(第三版)课后习题7.3 (C语言代码)浏览:619 |
C语言程序设计教程(第三版)课后习题10.1 (Java代码)浏览:1436 |
母牛的故事 (C语言代码)浏览:915 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:459 |
C语言训练-尼科彻斯定理 (C语言代码)浏览:463 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:464 |
C语言程序设计教程(第三版)课后习题9.6 (C语言代码)浏览:575 |
1113题解浏览:784 |
愚蠢的摄影师 (C++代码)浏览:933 |
C语言程序设计教程(第三版)课后习题5.5 (C语言代码)浏览:553 |