每日一题 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
相关推荐
王仔小奶13 分钟前
慢SQL治理与性能调优:DBA如何用Shell/Python提升运维效率?
python·sql·dba
用户03321266636717 分钟前
使用 Python 快速在 PowerPoint 中生成表格【教程】
python
邵奈一23 分钟前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS10023 分钟前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
夜晚回家30 分钟前
Python 身份运算符详解 | is 与 == 到底差在哪
python
fengye20716132 分钟前
cpython框架结构
python
shehuiyuelaiyuehao37 分钟前
算法56,重排链表
数据结构·算法·链表
用户912940468484241 分钟前
大模型返回 JSON 后,先过这道 Python 校验
python
Dmz丶1 小时前
前端转 AI 100 天 Day 32:LLM 客户端工程化——重试、超时、降级、限流
python