LeetCode Biweekly Contest No. 81 (2/4)

该博客讨论了一道关于无向图中不可达节点对计数的算法问题。通过使用并查集数据结构,可以将图中的节点分成多个连通分量,然后计算每个连通分量内的边数,最后根据组合数学公式计算不可达节点对的总数。博主给出了详细的解题思路,包括如何使用并查集进行节点分组,以及如何计算不可达节点对的数量。算法的时间复杂度为O(Nlog(N)),空间复杂度为O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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如果组成一个完全图,则共有C_{n}^{2}条边。假设共有k个小团体,每个小团体两两reachable,所以共有C_{k_i}^{2}条边,其中k_i为第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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值