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;
}
};