2316. Count Unreachable Pairs of Nodes in an Undirected Graph

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; // 当前连通分量中的节点数,包含自身,注意该值仅当该节点为 root 节点时有效,换句话说 size[i] 为当前节点为根节点时的节点数,如果当前节点有 parent 节点,则 size[i] 无法表示整个树的节点数

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]); // 路径压缩无需更新 size 数组,因为 size 数组仅存储 root 节点的连通分量的节点数,此时我们未修改 root 节点的 parent 指向,所以无需更新 size 数组
}

return parent[x]; // 注意此处是 parent[x] 而不是 x, 因为 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)); // 注意要获取根节点的 size, 因为只有根节点的 size 才能表示该连通分量中的节点个数
}

return pairs / 2; // 注意因为每条边被统计了两次,所以此处需要除以 2
}
}

需要加深对 size 数组的理解,且在路径压缩时无需维护 size 数组,这点是与 399 题最大的不同。

References

2316. Count Unreachable Pairs of Nodes in an Undirected Graph
详解:并查集(Union-Find)🔥🔥🔥