Problem 2. 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
题目描述:
You are given an integer n
. There is an undirected graph with n
nodes, numbered from 0
to n - 1
. You are given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi
.
Return the number of pairs of different nodes that are unreachable from each other.
Example 1:
Input: n = 3, edges = [[0,1],[0,2],[1,2]] Output: 0 Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
Example 2:
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] Output: 14 Explanation: There are 14 pairs of nodes that are unreachable from each other: [[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]]. Therefore, we return 14.
Constraints:
1 <= n <= 10^5
0 <= edges.length <= 2 * 10^5
edges[i].length == 2
0 <= ai, bi < n
ai != bi
- There are no repeated edges.
解题思路:
题目中给了一个无向图,其中一部分node之间有edge连接。
两个node之间只要有若干edge连接,则认为这两个node是reachable的。
问的是,所有unreachable的edge的个数。
以Example 2为例,n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
注意到,0、2、4、5这4个node组成了一个圈子,成为了一个小团体,这个小团体之间彼此之间互相连接,互相reachable,
同理,1、6两个node组成了一个小团体,
而3自己组成了一个小团体。
我们知道,n个node如果组成一个完全图,则共有条边。假设共有k个小团体,每个小团体两两reachable,所以共有
条边,其中
为第i个小团体的node个数,把所有小团体的边减掉,剩下的就是所有两两unreachable的node的edge的个数。
接下来问题在于,题目中给出的仅仅是每个小团体之间的部分的边,以及并没有帮我们把小团体分好组。
于是,我们的问题分为两个:
1. 分好小团体,计算出每个小团体的node的个数
2. 用全部的边的个数减掉所有小团体内边的个数
其中第一个问题可以用并查集来解决,第二个问题用组合数进行减法即可。
于是,并查集类定义为:
class UnionFind:
def __init__(self, N):
self._id = list(range(N))
self._count = N
self._rank = [0] * N
def find(self, p):
id = self._id
while p != id[p]:
id[p] = p = id[id[p]] # Path compression using halving.
return p
def count(self):
return self._count
def connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
id = self._id
rank = self._rank
i = self.find(p)
j = self.find(q)
if i == j:
return
self._count -= 1
if rank[i] < rank[j]:
id[i] = j
elif rank[i] > rank[j]:
id[j] = i
else:
id[j] = i
rank[i] += 1
def is_percolate(self):
return len(self._id) == 1
def __str__(self):
return " ".join([str(x) for x in self._id])
def __repr__(self):
return "UF(" + str(self) + ")"
解题类为:
class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
uf = UnionFind(n)
for e1, e2 in edges:
uf.union(e1, e2)
res = collections.defaultdict(int)
for i in range(n):
res[uf.find(i)] += 1
ret = n * (n - 1) // 2
for v in res.values():
ret -= v * (v - 1) // 2
return ret
时间复杂度:O(N log(N)),并查集可以用平衡树,达到几乎线性O(N loglog(N))
额外空间复杂度:O(N)