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;
    }
};
相关推荐
Song18 分钟前
C++:求梯形面积
开发语言·c++
十年一梦实验室1 小时前
【C++】相机标定源码笔记- RGB 相机与 ToF 深度传感器校准类
开发语言·c++·笔记·数码相机·计算机视觉
蜉蝣之翼❉1 小时前
c++ 简单线程池
开发语言·c++
shuai132_2 小时前
关于std::memory_order_consume
开发语言·c++
CylMK3 小时前
NOI大纲——普及组——二叉搜索树
开发语言·数据结构·c++·算法
Smark.3 小时前
06.01_111期_C++_unordermap_unorderset
开发语言·c++
码力码力我爱你4 小时前
C++ 实现QT信号槽
开发语言·c++·qt
季截4 小时前
QSettings会自动关闭文件句柄吗
c++
Verdure陌矣4 小时前
C++ STL容器:序列式容器-链list,forward_list
c++·stl·list
Once_day5 小时前
chrome-base源码分析(1)macros模块
c++·chrome