834. Sum of Distances in Tree —— weekly contest 84
Posted jinjin-2018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了834. Sum of Distances in Tree —— weekly contest 84相关的知识,希望对你有一定的参考价值。
Sum of Distances in Tree
An undirected, connected tree with N
nodes labelled 0...N-1
and N-1
edges
are given.
The i
th edge connects nodes edges[i][0]
and edges[i][1]
together.
Return a list ans
, where ans[i]
is the sum of the distances between node i
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:
Here is a diagram of the given tree:
0
/ 1 2
/| 3 4 5
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.
Note: 1 <= N <= 10000
1 class Solution { 2 public: 3 //相当于图来存来处理 4 vector<vector<int>> tree; 5 vector<int> res; 6 vector<int> subc; 7 int n; 8 vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) { 9 //tree.rvec(N,vector<int>(N)); 10 //init 11 n = N; 12 tree.resize(N); //初始化的函数 13 res.assign(N,0); 14 subc.assign(N,0); 15 //build tree 16 for(auto e : edges){ //遍历的技巧 17 tree[e[0]].push_back(e[1]); 18 tree[e[1]].push_back(e[0]); 19 } 20 set<int> visited1; 21 set<int> visited2; 22 DFS_POST(0,visited1); //初始root任何值都行 23 DFS_PRE(0,visited2); 24 return res; 25 26 } 27 void DFS_POST(int root,set<int> &visited){ //传引用保存修改值 28 visited.insert(root); 29 for(auto i : tree[root]){ 30 if(visited.find(i) == visited.end() ){ 31 DFS_POST(i,visited); 32 subc[root] += subc[i]; 33 res[root] += res[i] + subc[i]; 34 } 35 } 36 subc[root]++; //加上自身节点 37 } 38 void DFS_PRE(int root,set<int> &visited){ 39 visited.insert(root); 40 for(auto i : tree[root]){ 41 if(visited.find(i) == visited.end()){ 42 res[i] = res[root] - subc[i] + n - subc[i]; //算法核心 43 DFS_PRE(i,visited); 44 } 45 } 46 } 47 48 };
主要函数是初始化的函数。
主要算法思想是先序和后续的递归遍历(DFS)。
实现O(n2)的算法核心方程是:res[i] = res[root] - subc[i] + n - subc[i];
以上是关于834. Sum of Distances in Tree —— weekly contest 84的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 834. Sum of Distances in Tree 树中距离之和
Leetcode-1085 sum of digits in the minimum number(最小元素各数位之和)
pandas使用isna函数和sum函数统计dataframe包含的缺失值的总数(count number of missing values in dataframe)
pandas使用groupby函数和cumsum函数计算每个分组内的数值累加值并生成新的dataframe数据列( cumulative sum of each group in dataframe
[LeetCode in Python] 5403 (H) find the kth smallest sum of a matrix with sorted rows 有序矩阵中的第 k 个最小数组