3067. 在带权树网络中统计可连接服务器对数目

3067. 在带权树网络中统计可连接服务器对数目


题目链接:3067. 在带权树网络中统计可连接服务器对数目

代码如下:

cpp 复制代码
//参考链接:https://leetcode.cn/problems/count-pairs-of-connectable-servers-in-a-weighted-tree-network/solutions/2664330/mei-ju-gen-dfs-cheng-fa-yuan-li-pythonja-ivw5
class Solution 
{
public:
    vector<int> countPairsOfConnectableServers(vector<vector<int>>& edges, int signalSpeed) 
    {
        int n=edges.size()+1;
        vector<vector<pair<int,int>>> g(n);
        for(const auto& edge:edges)//建图
        {
            g[edge[0]].push_back({edge[1],edge[2]});
            g[edge[1]].push_back({edge[0],edge[2]});
        }

        function<int(int,int,int)> dfs=[&](int x,int fa,int sum)->int
        {
            int count=sum%signalSpeed==0;
            for(auto&[y,weight]:g[x])
            {
                if(y!=fa)
                {
                    count+=dfs(y,x,sum+weight);
                }
            }
            return count;
        };

        vector<int> res(n);
        for(int i=0;i<n;i++)
        {
            int sum=0;
            for(const auto&[y,weight]:g[i])
            {
                int count=dfs(y,i,weight);
                res[i]+=count*sum;
                sum+=count;
            }
        }
        return res;
    }
};
相关推荐
杨小码不BUG43 分钟前
蛇形舞动:矩阵填充的艺术与算法(洛谷P5731)
c++·算法·矩阵·csp-j/s·循环控制
草莓熊Lotso1 小时前
《C++ STL list 完全指南:从基础操作到特性对比,解锁链表容器高效用法》
开发语言·c++·list
繁星星繁2 小时前
C++11学习笔记
c++·笔记·学习
Stanford_11067 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
千里马-horse9 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
Lucis__10 小时前
再探类&对象——C++入门进阶
开发语言·c++
北京不会遇到西雅图11 小时前
【SLAM】【后端优化】不同优化方法对比
c++·机器人
jndingxin11 小时前
c++多线程(6)------ 条件变量
开发语言·c++
程序员莫小特11 小时前
老题新解|大整数加法
数据结构·c++·算法
洲覆13 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++