Sum of Distances in Tree

An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given.

The ith 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的更多相关文章

  1. [LeetCode] 834. Sum of Distances in Tree 树中距离之和

    An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given. The ith edge co ...

  2. [LeetCode] 834. Sum of Distances in Tree

    LeetCode刷题记录 传送门 Description An undirected, connected treewith N nodes labelled 0...N-1 and N-1 edge ...

  3. 【leetcode】834. Sum of Distances in Tree(图算法)

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

  4. [Swift]LeetCode834. 树中距离之和 | Sum of Distances in Tree

    An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given. The ith edge co ...

  5. 树中的路径和 Sum of Distances in Tree

    2019-03-28 15:25:43 问题描述: 问题求解: 写过的最好的Hard题之一. 初看本题,很经典的路径和嘛,dfs一遍肯定可以得到某个节点到其他所有节点的距离和.这种算法的时间复杂度是O ...

  6. leetcode834 Sum of Distances in Tree

    思路: 树形dp. 实现: class Solution { public: void dfs(int root, int p, vector<vector<int>>& ...

  7. 835. Image Overlap —— weekly contest 84

    Image Overlap Two images A and B are given, represented as binary, square matrices of the same size. ...

  8. 833. Find And Replace in String —— weekly contest 84

    Find And Replace in String To some string S, we will perform some replacement operations that replac ...

  9. 832. Flipping an Image —— weekly contest 84

    Flipping an Image Given a binary matrix A, we want to flip the image horizontally, then invert it, a ...

随机推荐

  1. opencv 中从cv::line和resize()函数

    转自: https://blog.csdn.net/weixin_36340947/article/details/77095924 转自: https://blog.csdn.net/robinhj ...

  2. MATLAB鼠标事件

    来源:https://blog.csdn.net/weixin_39090239/article/details/80586930 前记: 人机交互的方式--键盘开关.鼠标.触摸屏.体感传感器(Kin ...

  3. 【题解】小M的作物

    题目戳我 \(\text{Solution:}\) 这题要求最大收获,可以转化为所有可能的收益减去最小割. 单个点很好连边 \((S\to pos\to T),\) 问题在于如何处理组合的点. 观察到 ...

  4. devops-持续集成管理之SonarQube

    1. devops-持续集成管理之SonarQube  1) 代码质量七宗罪 编码规范:是否遵守了编码规范,遵循了最佳实践. 潜在的BUG:可能在最坏情况下出现问题的代码,以及存在安全漏洞的代码. 文 ...

  5. 第3天 | 12天搞定Python,用VSCode编写代码

    Visual Studio Code (简称 VS Code), 是一款免费并且开源的现代化轻量级代码编辑器,支持语法高亮.智能代码补全.自定义热键.括号匹配.代码片段等特性,并针对网页开发做了优化. ...

  6. C++ 构造函数、拷贝构造函数、赋值运算符

    <C++ Primer Plus> 12.1 动态内存和类 12.1.1 复习示例和静态类成员 不能在类声明中初始化静态成员变量,这是因为声明描述了如何分配内存,但并不分配内存 如果在头文 ...

  7. python -re库

    正则表达式的语法 正则表达式语法由字符和操作符构成 正则表达式的常用操作符: print("--正则表达式常用操作符--") mata="11356352135 abcd ...

  8. Centos6.X 手动升级gcc

    操作环境 CentOS6.5 64bit,gcc原版本为4.4.7,不能支持C++11的特性,所以需要升级 [root@zengxj ~]# wget http://ftp.gnu.org/gnu/g ...

  9. jdk可视化工具系列——检视阅读

    jdk可视化工具系列--检视阅读 参考 java虚拟机系列 RednaxelaFX知乎问答 RednaxelaFX博客 JConsole--Java监视与管理控制台 jconsole介绍 JConso ...

  10. 在centos下启动nginx出现Failed to start nginx.service:unit not found

    错误的原因就是没有添加nginx服务,所以启动失败. 解决方法: 1.    在/root/etc/init.d/目录下新建文件,文件名为nginx 或者用命令在根目录下执行:# vim /etc/i ...