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;
    }
};
相关推荐
6Hzlia4 分钟前
【Hot 100 刷题计划】 LeetCode 45. 跳跃游戏 II | C++ 贪心算法最优解题解
c++·leetcode·游戏
森G27 分钟前
48、柱状图---------QChart
c++·qt
Tanecious.33 分钟前
蓝桥杯备赛:Day8-小苯的异或和
c++·蓝桥杯
王老师青少年编程40 分钟前
csp信奥赛c++中的递归和递推研究
c++·算法·递归·递推·csp·信奥赛
样例过了就是过了1 小时前
LeetCode热题100 跳跃游戏
c++·算法·leetcode·贪心算法·动态规划
chen_ever1 小时前
从网络基础到吃透 Linux 高并发 I/O 核心(epoll+零拷贝 完整版)
linux·网络·c++·后端
无限进步_1 小时前
【C++&string】寻找字符串中第一个唯一字符:两种经典解法详解
开发语言·c++·git·算法·github·哈希算法·visual studio
小此方1 小时前
Re:思考·重建·记录 现代C++ C++11篇 (二) 右值引用与移动语义&引用折叠与完美转发
开发语言·c++·c++11·现代c++
深邃-2 小时前
【C语言】-数据在内存中的存储(1)
c语言·开发语言·数据结构·c++·算法
xiaoye-duck2 小时前
《算法题讲解指南:优选算法-字符串》--61.最长公共前缀,62.最长回文子串,63.二进制求和,64.字符串相乘
c++·算法·字符串