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;
    }
};
相关推荐
Cx330❀5 分钟前
【MySQL基础】详解MySQL数据类型:底层原理、越界测试与最佳实践
linux·开发语言·数据库·c++·mysql
星恒随风9 分钟前
C++ string 入门(一)
开发语言·c++·笔记·学习
旖-旎9 分钟前
《LeetCode 200 FloodFill 岛屿数量DFS解法》
c++·算法·深度优先·力扣·floodfill
前进吧-程序员17 分钟前
反转链表完全指南:辅助容器、三指针、头插法
数据结构·c++·链表
我不是懒洋洋19 分钟前
从零实现一个分布式配置中心:服务发现与热更新
c++
省四收割者21 分钟前
从硬件中断到分布式协程:全景解构高并发机制与 C / Golang 的巅峰对决
c++·分布式·嵌入式硬件·golang
Cx330❀25 分钟前
【Linux网络】从零定制应用层协议:黏包问题、全双工缓冲区与 Jsoncpp 序列化深度解析
linux·运维·服务器·开发语言·网络·c++·人工智能
江屿风30 分钟前
C++图论基础Bellman-Ford与spfa算法如何判断负环
开发语言·c++·笔记·算法·图论
森G37 分钟前
68、项目配置和示例---------多媒体
c++·qt
进击的荆棘1 小时前
优选算法——BFS
c++·算法·leetcode·宽度优先