[LeetCode] 834. Sum of Distances in Tree
Description
An undirected, connected treewith 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
思路
题意:给出一棵树,求出树上每个节点到其他节点的距离总和。
题解:每个节点保存两个值,一个是其子树的节点个数(包括自身节点也要计数)nodesum[ ],一个是其子树各点到它的距离 dp[ ],那么我们假设根节点为 u ,其仅有一个儿子 v , u 到 v 的距离为 1 ,而 v 有若干儿子节点,那么 dp[v] 表示 v 的子树各点到 v 的距离和,那么各个节点到达 u 的距离便可以这样计算: dp[u] = dp[v] + nodesum[ v ] *1; (式子的理解,v 的一个儿子节点为 f,那么 f 到达 u 的距离为 (sum[ f ->v] + sum [v- > u])*1 ,dp[v] 包含了 sum[f->v]*1,所以也就是式子的分配式推广到各个子节点计算出来的和)。我们已经知道了各个节点到达根节点的距离和,那么从根节点开始递推下来可以得到各个点的距离和。另开一个数组表示每个节点的到其他节点的距离和,那么对于根节点u来说, dissum[u] = dp[u]。以 u 的儿子 v 为例, v 的子节点到 v 不必经过 v->u 这条路径,因此 dissum[u] 多了 nodesum[v] * 1,但是对于不是 v 的子节点的节点,只到达了 u ,因此要到达 v 必须多走 u->v 这条路径,因此 dissum[u] 少了 ( N - nodesum[v] ) * 1) ,所以 dissum[v] = dissum[u] - nodesum[v] * 1 + (N - nodesum[v] ) * 1,按照这个方法递推下去就可以得到各个点的距离和。
1 class Solution {
2 private int tot = ;
3 private Edge[] edge;
4 private int[] head;
5 private int[] dp;
6 private int[] nodesum;
7 private int[] dissum;
8 public int[] sumOfDistancesInTree(int N, int[][] edges) {
9 edge = new Edge[ * N + ];
10 head = new int[N + ];
11 dp = new int[N + ];
12 nodesum = new int[N + ];
13 dissum = new int[N];
14 Arrays.fill(head,-);
15 for (int i = ;i < edges.length;i++){
16 int u = edges[i][];
17 int v = edges[i][];
18 addedge(u,v);
19 addedge(v,u);
20 }
21 dfs1(,);
22 dissum[] = dp[];
23 dfs2(,,N);
24 return dissum;
25 }
26
27 public void addedge(int u,int v){
28 edge[tot] = new Edge();
29 edge[tot].u = u;
30 edge[tot].v = v;
31 edge[tot].next = head[u];
32 head[u] = tot++;
33 }
34
35 public void dfs1(int u,int fa){
36 dp[u] = ;
37 nodesum[u] = ;
38 for (int i = head[u];i != -;i = edge[i].next){
39 int v = edge[i].v;
40 if (v == fa) continue;
41 dfs1(v,u);
42 dp[u] += dp[v] + nodesum[v];
43 nodesum[u] += nodesum[v];
44 }
45 }
46
47 public void dfs2(int u,int fa,int sum){
48 for (int i = head[u];i != -;i = edge[i].next){
49 int v = edge[i].v;
50 if (v == fa) continue;
51 dissum[v] = dissum[u] - nodesum[v] + sum - nodesum[v];
52 dfs2(v,u,sum);
53 }
54 }
55 class Edge{
56 int u,v,next;
57 }
58 }
[LeetCode] 834. Sum of Distances in Tree的更多相关文章
- [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 ...
- 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 a ...
- 【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 ...
- [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 ...
- 树中的路径和 Sum of Distances in Tree
2019-03-28 15:25:43 问题描述: 问题求解: 写过的最好的Hard题之一. 初看本题,很经典的路径和嘛,dfs一遍肯定可以得到某个节点到其他所有节点的距离和.这种算法的时间复杂度是O ...
- leetcode834 Sum of Distances in Tree
思路: 树形dp. 实现: class Solution { public: void dfs(int root, int p, vector<vector<int>>& ...
- LeetCode:Path Sum I II
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...
- [LeetCode#110, 112, 113]Balanced Binary Tree, Path Sum, Path Sum II
Problem 1 [Balanced Binary Tree] Given a binary tree, determine if it is height-balanced. For this p ...
- [LeetCode] Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
随机推荐
- Oracle锁表信息处理步骤
查看是否有锁表的sql select 'blocker(' || lb.sid || ':' || sb.username || ')-sql:' || qb.sql_text blockers, ' ...
- 001-supervisor
supervisor 使用教程(转) 原文地址:https://word.gw1770df.cc/2016-08-04/linux/supervisor-%E4%BD%BF%E7%94%A8%E6%9 ...
- MySQL基础day03 存储引擎和外键MySQL 5.6
MySQL基础day03_存储引擎和外键-MySQL 5.6 外键的条件: 1,表的存储引擎为innodb存储引擎 2,表中外键字段的类型要与参考表的字段类型一致 3,外键字段要是索引类型中的一种 M ...
- [洛谷P2154] SDOI2009 虔诚的墓主人
问题描述 小W是一片新造公墓的管理人.公墓可以看成一块N×M的矩形,矩形的每个格点,要么种着一棵常青树,要么是一块还没有归属的墓地. 当地的居民都是非常虔诚的基督徒,他们愿意提前为自己找一块合适墓地. ...
- CSS——相对定位、绝对定位、固定定位
相对定位: position:relative 当元素被设置相对定位或是绝对定位后,将自动产生层叠,他们的层叠级别自然的高于文本流,除非设置其z-index值为负值. 并且我们发现当相对定位元素进行位 ...
- 【leetcode】1143. Longest Common Subsequence
题目如下: Given two strings text1 and text2, return the length of their longest common subsequence. A su ...
- 对SQL 优化,提升性能!
对SQL 进行优化能够有效提高SQL 语句的执行效率,降低系统资源开销,是开发者提高后端系统处理能力的首选方案. 新产品上线后,随着运营推广活动的开始,业务进入快速增长期,数据库作为后端系统唯一或者主 ...
- Linux内核设计与实现 总结笔记(第十二章)内存管理
内核里的内存分配不像其他地方分配内存那么容易,内核的内存分配不能简单便捷的使用,分配机制也不能太复杂. 一.页 内核把页作为内存管理的基本单位,尽管处理器最小寻址坑是是字或者字节.但是内存管理单元MM ...
- 大文件上传-大视频上传,T级别的,求解决方案
第一点:Java代码实现文件上传 FormFile file = manform.getFile(); String newfileName = null; String newpathname = ...
- Codeforce |Educational Codeforces Round 77 (Rated for Div. 2) B. Obtain Two Zeroes
B. Obtain Two Zeroes time limit per test 1 second memory limit per test 256 megabytes input standard ...