每日一题 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
相关推荐
mit6.8242 小时前
bfs|栈
算法
青瓷程序设计2 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95272 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z3 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu3 小时前
一文入门 LangGraph 开发
python·ai
CoderYanger3 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz4 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗4 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java4 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*4 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven