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;
    }
};
相关推荐
沐雪轻挽萤5 分钟前
6. C++17新特性-编译期 if 语句 (if constexpr)
开发语言·c++
apcipot_rain20 分钟前
【天梯赛】2026天梯赛模拟赛——题解
开发语言·c++·算法·蓝桥杯·天梯赛
-To be number.wan23 分钟前
重新认识一下“私有继承”
c++·学习
江奖蒋犟1 小时前
【C++】红黑树
开发语言·c++
lclin_20201 小时前
【大恒相机】C++ 设备枚举+打开关闭+启停采集(基础入门)
c++·工业相机·大恒相机·galaxysdk
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 131. 分割回文串 | C++ 回溯算法基础切割法
c++·算法·leetcode
山栀shanzhi2 小时前
FFmpeg编码封装流程骨架
c++·ffmpeg
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 1143. 最长公共子序列 | C++ 二维DP 与 哨兵技巧
c++·算法·leetcode
Hical_W2 小时前
告别回调地狱:在 C++ Web 框架中全面拥抱协程
c++·github
炘爚2 小时前
C++多线程编程:join与detach的致命陷阱
c++