每日一题 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
相关推荐
gihigo19985 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia6 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia6 小时前
go(基础08)——多态
算法·golang
leoufung6 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
ID_180079054736 小时前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
Q_Q5110082857 小时前
python+django/flask+vue的大健康养老公寓管理系统
spring boot·python·django·flask·node.js
我是哈哈hh7 小时前
【Python数据分析】Numpy总结
开发语言·python·数据挖掘·数据分析·numpy·python数据分析
Michelle80237 小时前
24大数据 14-2 函数练习
开发语言·python
qq_381454997 小时前
Python学习技巧
开发语言·python·学习
im_AMBER7 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法