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;
    }
};
相关推荐
敲上瘾6 小时前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3
人间乄惊鸿客13 小时前
c++ 右值
c++·算法
ShineWinsu15 小时前
对于Qt:TCP的解析
linux·c++·qt·网络协议·面试·tcp·客户端
瑶池酒剑仙15 小时前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio
郝学胜-神的一滴2 天前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
旖旎夜光2 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
青少儿编程课堂2 天前
蓝桥杯真题解析:手链配色计数与波利亚定理(全国青少年信息素养大赛与电子学会软件编程考级)
c++·python·算法·bfs·信息学竞赛
艾莉丝努力练剑2 天前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
旖旎夜光2 天前
面试题 01.02: 判定是否互为字符重排 (哈希表) —— 题解
c++·笔记·学习·算法·哈希表
白小飞不会飞2 天前
【AUTOSAR】CP SOME/IP-TP
c++·嵌入式硬件·网络协议·车载系统·autosar