目录
3067. 在带权树网络中统计可连接服务器对数目
题目描述:
给你一棵无根带权树,树中总共有 n
个节点,分别表示 n
个服务器,服务器从 0
到 n - 1
编号。同时给你一个数组 edges
,其中 edges[i] = [ai, bi, weighti]
表示节点 ai
和 bi
之间有一条双向边,边的权值为 weighti
。再给你一个整数 signalSpeed
。
如果两个服务器 a
,b
和 c
满足以下条件,那么我们称服务器 a
和 b
是通过服务器 c
可连接的 :
a < b
,a != c
且b != c
。- 从
c
到a
的距离是可以被signalSpeed
整除的。 - 从
c
到b
的距离是可以被signalSpeed
整除的。 - 从
c
到b
的路径与从c
到a
的路径没有任何公共边。
请你返回一个长度为 n
的整数数组 count
,其中 count[i]
表示通过服务器 i
可连接 的服务器对的 数目 。
示例 1:
输入:edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1 输出:[0,4,6,6,4,0] 解释:由于 signalSpeed 等于 1 ,count[c] 等于所有从 c 开始且没有公共边的路径对数目。 在输入图中,count[c] 等于服务器 c 左边服务器数目乘以右边服务器数目。
示例 2:
输入:edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3 输出:[2,0,0,0,0,0,2] 解释:通过服务器 0 ,有 2 个可连接服务器对(4, 5) 和 (4, 6) 。 通过服务器 6 ,有 2 个可连接服务器对 (4, 5) 和 (0, 5) 。 所有服务器对都必须通过服务器 0 或 6 才可连接,所以其他服务器对应的可连接服务器对数目都为 0 。
提示:
2 <= n <= 1000
edges.length == n - 1
edges[i].length == 3
0 <= ai, bi < n
edges[i] = [ai, bi, weighti]
1 <= weighti <= 106
1 <= signalSpeed <= 106
- 输入保证
edges
构成一棵合法的树。
实现代码与解析:
原理思路:
class Solution {
int N = 1010;
int[] e = new int[N * 2], ne = new int[N * 2], h = new int[N], w = new int[N * 2];
int idx;
public void add(int a, int b, int c) {
e[idx] = b;w[idx] = c; ne[idx] = h[a]; h[a] = idx++;
}
public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) {
Arrays.fill(h, -1);
for (int[] t: edges) {
int a = t[0];
int b = t[1];
int c = t[2];
add(a, b, c);
add(b, a, c);
}
int[] res = new int[edges.length + 1];
for (int i = 0; i < edges.length + 1; i++) {
int s = 0;
for (int j = h[i]; j != -1; j = ne[j]) {
int k = e[j]; // 相邻节点
int c = w[j]; // 权重
int t = dfs(k, c, signalSpeed, i);
res[i] += s * t;
s += t;
}
}
return res;
}
public int dfs(int cur, int sum, int signalSpeed, int fa) {
int cnt = sum % signalSpeed == 0 ? 1 : 0;
for (int i = h[cur]; i != -1; i = ne[i]) {
int j = e[i];
int c = w[i];
if (j == fa) continue;
cnt += dfs(j, sum + c, signalSpeed, cur);
}
return cnt;
}
}
原理思路:
遍历每一个节点t,然后dfs每个t的相邻节点,求出每个相邻节点构成的子树中符合路径可以被 signalSpeed
整除的节点个数,最后从左向右相乘相加。