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;
    }
};
相关推荐
上去我就QWER17 小时前
Qt快捷键“魔法师”:QKeySequence
开发语言·c++·qt
将编程培养成爱好20 小时前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
猿太极20 小时前
设计模式学习(3)-行为型模式
c++·设计模式
随意起个昵称21 小时前
【递归】二进制字符串中的第K位
c++·算法
mjhcsp1 天前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
Mr_WangAndy1 天前
C++_chapter15_C++重要知识点_lambda,initializer_list
c++·lambda·初始化列表
Maple_land1 天前
第1篇:Linux工具复盘上篇:yum与vim
linux·运维·服务器·c++·centos
hggngx548h1 天前
有哪些C++20特性可以在Dev-C++中使用?
开发语言·c++·c++20
计科土狗1 天前
算法基础入门第一章
c++·算法
9ilk1 天前
【仿RabbitMQ的发布订阅式消息队列】 ---- 功能测试联调
linux·服务器·c++·分布式·学习·rabbitmq