UnionFind(TLE)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| class Solution { private static class UnionFind { private final int[] parent;
public UnionFind(int n) { this.parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } }
public void union(int x, int y) { int xRoot = getRoot(x), yRoot = getRoot(y); if (xRoot == yRoot) { return; }
parent[xRoot] = yRoot; }
private int getRoot(int x) { if (parent[x] != x) { parent[x] = getRoot(parent[x]); }
return parent[x]; }
public boolean isConnected(int x, int y) { return getRoot(x) == getRoot(y); } }
public long countPairs(int n, int[][] edges) { UnionFind unionFind = new UnionFind(n);
for (int[] edge : edges) { unionFind.union(edge[0], edge[1]); }
long pairs = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (!unionFind.isConnected(i, j)) { pairs++; } } }
return pairs; } }
|
UnionFind
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution { private static class UnionFind { private final int[] parent; private final int[] size;
public UnionFind(int n) { this.parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } this.size = new int[n]; Arrays.fill(size, 1); }
public void union(int x, int y) { int xRoot = getRoot(x), yRoot = getRoot(y); if (xRoot == yRoot) { return; }
if (size[xRoot] < size[yRoot]) { parent[xRoot] = yRoot; size[yRoot] += size[xRoot]; } else { parent[yRoot] = xRoot; size[xRoot] += size[yRoot]; } }
private int getRoot(int x) { if (parent[x] != x) { parent[x] = getRoot(parent[x]); }
return parent[x]; }
public int getSize(int x) { return size[x]; } }
public long countPairs(int n, int[][] edges) { UnionFind unionFind = new UnionFind(n);
for (int[] edge : edges) { unionFind.union(edge[0], edge[1]); }
long pairs = 0; for (int i = 0; i < n; i++) { pairs += n - unionFind.getSize(unionFind.getRoot(i)); }
return pairs / 2; } }
|
需要加深对 size 数组的理解,且在路径压缩时无需维护 size 数组,这点是与 399 题最大的不同。
References
2316. Count Unreachable Pairs of Nodes in an Undirected Graph
详解:并查集(Union-Find)🔥🔥🔥