代码拉取完成,页面将自动刷新
import java.util.*;
public class _834 {
static class Solution1{
public int[] sumOfDistancesInTree(int n, int[][] edges) {
//dfs 2次,
//第一次从0开始,统计res[0],以及count[i];
// if(edges.length == 0) return new int[n];
Map<Integer, Set<Integer>> graph = new HashMap<>();
for(int[] edge : edges){
graph.computeIfAbsent(edge[0],k->new HashSet<>()).add(edge[1]);
graph.computeIfAbsent(edge[1],k->new HashSet<>()).add(edge[0]);
}
int[] res = new int[n];
int[] count = new int[n];
System.out.println(graph);
res[0] = computeCurDistanceAndCurCount(graph,count,0,-1,0);
computeRes(graph,count,res,0,-1);
return res;
}
public int computeCurDistanceAndCurCount(Map<Integer,Set<Integer>> graph,int[] count,int cur,int pre,int deep){
count[cur] = 1;
int res = deep;
for(int child : graph.getOrDefault(cur, Collections.emptySet())){
if(child == pre) continue;
res += computeCurDistanceAndCurCount(graph,count,child,cur,deep+1);
count[cur] += count[child];
}
return res;
}
public void computeRes(Map<Integer,Set<Integer>> graph,int[] count,int[] res,int cur,int pre){
// if(pre == cur) return ;
for(int child : graph.getOrDefault(cur,Collections.emptySet())){
if(child == pre) continue;
res[child] = res[cur] + count.length - 2 * count[child];
computeRes(graph,count,res,child,cur);
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。