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;
    }
};
相关推荐
2301_803554524 小时前
c++中的绑定器
开发语言·c++·算法
海棠蚀omo4 小时前
C++笔记-位图和布隆过滤器
开发语言·c++·笔记
消失的旧时光-19435 小时前
c++ 的标准库 --- std::
c++·jni
GiraKoo5 小时前
【GiraKoo】C++11的新特性
c++·后端
不午睡的探索者5 小时前
告别性能瓶颈!Python 量化工程师,进击 C++ 高性能量化交易的“必修课”!
c++·github
OpenC++5 小时前
【C++】观察者模式
c++·观察者模式·设计模式
老歌老听老掉牙5 小时前
粒子群优化算法实现与多维函数优化应用
c++·pso·粒子群算法
myloveasuka5 小时前
信号操作集函数
linux·运维·服务器·c语言·c++·vscode
山野万里__6 小时前
C++与Java内存共享技术:跨平台与跨语言实现指南
android·java·c++·笔记
Mr_Xuhhh6 小时前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法