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;
    }
};
相关推荐
用户805533698031 分钟前
现代Qt开发教程(新手篇)1.11——定时器
c++·qt
澈2078 分钟前
STL迭代器:容器遍历的万能钥匙
开发语言·c++
azoo17 分钟前
emplace_back和push_back() 函数添加 cv::Point 类型数据
c++·opencv
样例过了就是过了1 小时前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
橙子也要努力变强2 小时前
信号的保存、阻塞与递达
linux·服务器·c++
旖-旎2 小时前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣
T0uken2 小时前
基于 vcpkg 与 LLVM-MinGW 的 Qt6 静态链接开发方案
c++·windows·qt
睡一觉就好了。3 小时前
C++11(一)
c++
水云桐程序员3 小时前
C++的主要应用场景
c++·学习方法