|
| 1 | +// Problem Number: 2685 |
| 2 | + |
| 3 | +// Count the Number of Complete Components. |
| 4 | + |
| 5 | +class UnionFind { |
| 6 | + public UnionFind(int n) { |
| 7 | + id = new int[n]; |
| 8 | + rank = new int[n]; |
| 9 | + nodeCount = new int[n]; |
| 10 | + edgeCount = new int[n]; |
| 11 | + for (int i = 0; i < n; ++i) { |
| 12 | + id[i] = i; |
| 13 | + nodeCount[i] = 1; |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + public void unionByRank(int u, int v) { |
| 18 | + final int i = find(u); |
| 19 | + final int j = find(v); |
| 20 | + ++edgeCount[i]; |
| 21 | + if (i == j) |
| 22 | + return; |
| 23 | + if (rank[i] < rank[j]) { |
| 24 | + id[i] = j; |
| 25 | + edgeCount[j] += edgeCount[i]; |
| 26 | + nodeCount[j] += nodeCount[i]; |
| 27 | + } else if (rank[i] > rank[j]) { |
| 28 | + id[j] = i; |
| 29 | + edgeCount[i] += edgeCount[j]; |
| 30 | + nodeCount[i] += nodeCount[j]; |
| 31 | + } else { |
| 32 | + id[i] = j; |
| 33 | + edgeCount[j] += edgeCount[i]; |
| 34 | + nodeCount[j] += nodeCount[i]; |
| 35 | + ++rank[j]; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public int find(int u) { |
| 40 | + return id[u] == u ? u : (id[u] = find(id[u])); |
| 41 | + } |
| 42 | + |
| 43 | + public boolean isComplete(int u) { |
| 44 | + return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u]; |
| 45 | + } |
| 46 | + |
| 47 | + private int[] id; |
| 48 | + private int[] rank; |
| 49 | + private int[] nodeCount; |
| 50 | + private int[] edgeCount; |
| 51 | +} |
| 52 | + |
| 53 | +class Solution { |
| 54 | + public int countCompleteComponents(int n, int[][] edges) { |
| 55 | + int ans = 0; |
| 56 | + UnionFind uf = new UnionFind(n); |
| 57 | + Set<Integer> parents = new HashSet<>(); |
| 58 | + |
| 59 | + for (int[] edge : edges) { |
| 60 | + final int u = edge[0]; |
| 61 | + final int v = edge[1]; |
| 62 | + uf.unionByRank(u, v); |
| 63 | + } |
| 64 | + |
| 65 | + for (int i = 0; i < n; ++i) { |
| 66 | + final int parent = uf.find(i); |
| 67 | + if (parents.add(parent) && uf.isComplete(parent)) |
| 68 | + ++ans; |
| 69 | + } |
| 70 | + |
| 71 | + return ans; |
| 72 | + } |
| 73 | +} |
0 commit comments