首页 > 其他分享 >LeetCode 834. Sum of Distances in Tree

LeetCode 834. Sum of Distances in Tree

时间:2024-03-23 23:35:18浏览次数:24  
标签:count Distances int tree Sum Tree edges res root

原题链接在这里:https://leetcode.com/problems/sum-of-distances-in-tree/description/

题目:

There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.

Example 1:

Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.

Example 2:

Input: n = 1, edges = []
Output: [0]

Example 3:

Input: n = 2, edges = [[1,0]]
Output: [1,1]

Constraints:

  • 1 <= n <= 3 * 104
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • The given input represents a valid tree.

题解:

Count the sum of distance from one node, then we can simply do a DFS and it takes O(n) time. 
For all the nodes, we need O(n^2).

But we can do it with two traversal.

First DFS, bottom up. Update the count of each subtree incluing itself. count[root] += count[child].

And update sum of distance for root, res[root] += res[child] + count[child]. Why? it is like 1 -> 2 -> 3, res[2] = 1, count[2] = 2, res[1] = 3. It contains 1 to 2 and 1 to 3.

Second DFS, top down. Udpate the res for all nodes. If we move root to its child. cound[child] nodes get closer to new root, n - count[child] get further from new root.

Time Complexity: O(n). n is the number of nodes in tree. DFS takes O(n + e). But it is a tree. Thus e = n - 1.

Space: O(n).

AC Java:

 1 class Solution {
 2     HashSet<Integer>[] tree;
 3     int [] res;
 4     int [] count;
 5     public int[] sumOfDistancesInTree(int n, int[][] edges) {
 6         tree = new HashSet[n];
 7         for(int i = 0; i < n; i++){
 8             tree[i] = new HashSet<Integer>();
 9         }
10         res = new int[n];
11         count = new int[n];
12         for(int [] e : edges){
13             tree[e[0]].add(e[1]);
14             tree[e[1]].add(e[0]);
15         }
16 
17         dfsCountRes(0, -1);
18         dfsRes(0, -1);
19         return res;
20     }
21 
22     private void dfsCountRes(int root, int parent){
23         for(int i : tree[root]){
24             if(i == parent){
25                 continue;
26             }
27 
28             dfsCountRes(i, root);
29             count[root] += count[i];
30             res[root] += res[i] + count[i];
31         }
32 
33         count[root]++;
34     }
35 
36     private void dfsRes(int root, int parent){
37         for(int i : tree[root]){
38             if(i == parent){
39                 continue;
40             }
41 
42             res[i] = res[root] - count[i] + count.length - count[i];
43             dfsRes(i, root);
44         }
45     }
46 }

 

标签:count,Distances,int,tree,Sum,Tree,edges,res,root
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18091898

相关文章

  • CF1628D1 Game on Sum (Easy Version) 题解
    题目传送门(EasyVersion)|题目传送门(HardVersion)前置知识博弈论解法CF1628D1GameonSum(EasyVersion)设\(x_{i}\)表示第\(i\)轮时Alice选择的数。设\(f_{i,j}\)表示已经进行了\(i\)轮,且使用了\(j\)次加法时的最大得分,状态转移方程为\(f_{i,j}=\ma......
  • Maximum Sum(Round 936)
    #include<bits/stdc++.h>#defineendl'\n'usingll=longlong;typedefunsignedlonglongull;usingnamespacestd;voidGordenGhost();constllmod=1e9+7;llmaxSum(vector<ll>a,intw){llsum=0;llb=0;for(inti......
  • Tree Cutting
    这道题目的代码的写法非常新,可以学习首先我们从\(x=1\)开始想起,此时显然一条边都不用切然后是\(x=2\),我们发现所有叶子节点都不能分离开来了,我们把所有叶子节点与其父亲节点弄成一个连通块,显然这里切掉是最优的,在考虑剩下的树,仍然对叶子节点实施这个操作,直到最后没有剩下的树为......
  • 递归法求解最大连续子序列和MaxSubSum
    何为递归呢总结一句话就是:向基准情形不断推进核心就在于“递”和“归”递:不断推进归:向基准情形结合今天的例子进一步解释如下:分而治之的思想divideandconquer分三步:“分”“治”“合并”“分”:将子序列看作三种,左半部分右半部分跨越中间元素的子序列“治”......
  • P1466 [USACO2.2] 集合 Subset Sums
    题目传送门:P1466[USACO2.2]集合SubsetSums-洛谷|计算机科学教育新生态(luogu.com.cn)https://www.luogu.com.cn/problem/P1466//https://www.luogu.com.cn/problem/P1466//背包#include<bits/stdc++.h>usingnamespacestd;intval[40],f[40][1005];//f[i][......
  • CF1930D1 - Sum over all Substrings (Easy Version)
    对于每一个\(f(i,j)\),我们考虑如何计算。我们发现,\(\texttt{1010}\)式的字符串很有用,所以这启发我们如果遇到了一个模式\(p_i=\texttt{'1'}\),那么我们可以在\(i+1\)的位置放一个\(\texttt{'1'}\)。这样我们直接处理了\(i,i+1,i+2\)。容易证明这是最优的。#incl......
  • CF1923E 一个无需 DSU On Tree 的解法(?
    在地铁上口胡了一下。不知道对不对。考虑记录每一个点\(i\)离他最远的一个祖先使得祖先到\(i\)的路径上没有\(a_i\)。设他为\(\text{lst}_i\)。然后如果两个\(u,v\)的\(\text{lst}\)相等,那么这条路径就是好的。每种颜色枚举即可。八成假了(?),欢迎Hack。PS:全对了,确实能......
  • tree --help 最新版 v2.1.1
    tree--helpusage:tree[-acdfghilnpqrstuvxACDFJQNSUX][-Llevel[-R]][-H baseHREF]    [-Ttitle][-ofilename][-Ppattern][-Ipattern][--gitignore]    [--gitfile[=]file][--matchdirs][--metafirst][--ignore-case]    [--nolinks]......
  • Kinetic Tournament Tree
    考虑这样一个问题:\(n\)个一次函数\(k_ix_i+b_i\),每个一次函数初始有\(x_i=0\);区间对\(x_i\)加正数\(x\),区间查询\(\max\limits_{i=l}^rk_ix_i+b_i\)。考虑每个点维护当\(x_i=0\)时值最大的函数,然后额外维护一个阈值\(t\),表示当\(x\)增大到\(t\)时这个......
  • leetcode 路经总和 pathsum
    很熟悉的一道题,XX二面做过,面试官没让我当场造树,让我用数组模拟树来运行,依旧跑出来了。但是刚刚再做了一下,没思路,不会写......