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;
    }
};
相关推荐
CoderCodingNo17 分钟前
【CSP】CSP-J 2019 江西真题 | 次大值 luogu-P5682 (适合GESP四、五级及以上考生练习)
开发语言·c++·算法
极客智造30 分钟前
深度详解 C++ 类型转换:隐式转换、C 风格强转、C++ 四大标准转换
c++·类型转换
橘颂TA2 小时前
【Linux】自旋锁
linux·开发语言·数据库·c++
珹洺2 小时前
C++AI多模型聊天系统(一)项目背景意义与整体架构、核心基类实现
c++·人工智能·架构
智者知已应修善业2 小时前
【51单片机ADC-MAX1241/ADC0832驱动】2023-6-6
c++·经验分享·笔记·算法·51单片机
珹洺2 小时前
C++AI多模型聊天系统(三)AI多模型(豆包/Kimi/千问)接入与实现
开发语言·c++·人工智能
tankeven2 小时前
动态规划专题(10):最优三角剖分问题
c++·算法·动态规划
weixin_468466853 小时前
排列组合算法之隔板问题与错排公式
c++·算法·数学建模·排列组合·竞赛·错排·隔板
wsoz3 小时前
Leetcode链表-day9
c++·算法·leetcode·链表
万法若空3 小时前
ANSI转义码详解
linux·c++