每日一题 2316. 统计无向图中无法互相到达点对数(中等,图连通分量)

  1. 题目很简单,只要求出每个连通分量有多少个节点即可
  2. 首先通过建立一个字典来表示每个节点的邻接关系
  3. 遍历每个节点,并通过邻接关系标记在当前连通分量内的所有的点,这样就可以知道一个连通分量内有多少个点
  4. 在这里我陷入了一个误区,导致最后超时,我一开始把所有的连通分量的点数都求出来之后,再将他们两两组合得到最后的答案(耗时O(a2) 其中a是连通分量的数量),而事实上对于每个连通分量它的组合数就是 cnt * (n - cnt) 只要 O(a) 就可以求出来,最后由于每一个点对都被计算了两次,因此需要 ans // 2
python 复制代码
class Solution:
    def countPairs(self, n: int, edges: List[List[int]]) -> int:
        d = defaultdict(list)
        isCnt = set()
        for i in range(len(edges)):
            d[edges[i][0]].append(edges[i][1])
            d[edges[i][1]].append(edges[i][0])
        ans = 0
        for i in range(n):
            if i in isCnt:
                continue
            cnt = 1
            l = d[i]
            isCnt.add(i)
            while len(l) > 0:
                newl = []
                for j in l:
                    if j in isCnt:
                        continue
                    newl.extend(d[j])
                    cnt += 1
                    isCnt.add(j)
                l = newl.copy()
            ans += cnt * (n - cnt)
        return ans // 2
相关推荐
金銀銅鐵5 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup119 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0011 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵13 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf14 小时前
Agent 流程编排
后端·python·agent
copyer_xyf14 小时前
Agent RAG
后端·python·agent
copyer_xyf14 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf15 小时前
Agent 记忆管理
后端·python·agent
JieE2121 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试