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;
    }
};
相关推荐
吗~喽几秒前
【C++】模板的两大特性
c++
王璐WL4 分钟前
【C++】string类基础知识
开发语言·c++
笑鸿的学习笔记4 分钟前
qt-C++语法笔记之Qt中的delete ui、ui的本质与Q_OBJECT
c++·笔记·qt
研究点啥好呢18 分钟前
3月21日GitHub热门项目推荐|攻守兼备,方得圆满
java·c++·python·开源·github
m0_5281744520 分钟前
ZLibrary反爬机制概述
开发语言·c++·算法
Yu_Lijing25 分钟前
基于C++的《Head First设计模式》笔记——责任链模式
c++·笔记·设计模式·责任链模式
yunyun3212341 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
Amnesia0_01 小时前
类型转换和特殊类
开发语言·c++
格林威1 小时前
C++ 工业视觉实战:Bayer 图转 RGB 的 3 种核心算法(邻域平均、双线性、OpenCV 源码级优化)
开发语言·c++·人工智能·opencv·算法·计算机视觉·工业相机
2401_851272991 小时前
C++中的模板方法模式
开发语言·c++·算法