每日一题 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
相关推荐
金銀銅鐵1 分钟前
[Python] 借助 Pillow 和 NumPy 生成与斐波那契数列有关的图案
python·数学
雪之下雪乃的代码日记7 分钟前
Python快速入门(Java开发者版)
java·开发语言·笔记·python
gb421528730 分钟前
python中pypdf库和langchain-unstructured库在解析pdf文件的时候的区别?
python·langchain·pdf
weixin1997010801635 分钟前
☁️《抖店API基础¥0.018/百次·增值¥0.05/百次:云内云外价差架构实战》(附Python源码)
开发语言·python·架构
0566461 小时前
Python数据结构——循环队列
python·学习
萌动的小火苗1 小时前
1、python基础面试题
java·开发语言·python
sunywz2 小时前
【从零搭建物联网智能充电桩系统】2、自定义二进制协议:设备为什么不用 JSON?
python·物联网·json
小叮当爱咖啡2 小时前
Day3.参数+Prompt三板斧
开发语言·python·prompt
菜冻鱼2 小时前
Python-pandas-索引与筛选
开发语言·笔记·python·numpy·pandas·学习方法
青 春 记 忆2 小时前
LeetCode 53. 最大子数组和|Python 解法详解
python·算法·leetcode