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;
    }
};
相关推荐
再卷也是菜1 小时前
C++17(下)
c++
alexwang2112 小时前
HDU 4348 详细题解
c++·算法·题解·hdu·主席树·可持久化数据结构·可持久化线段树
程序员zgh2 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
皓月斯语4 小时前
B2132 素数对
c++·算法·题解
星轨初途4 小时前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode
笨鸟先飞的橘猫5 小时前
c++面向对象编程
开发语言·c++
啦啦啦啦啦zzzz5 小时前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
-森屿安年-5 小时前
647. 回文子串
c++·算法·动态规划
fpcc6 小时前
c++应用网络编程之十七WebSocket
网络·c++·websocket
haolin123.6 小时前
类和对象(下)
c语言·开发语言·c++