首页 > 其他 > 详细

leetcode834 Sum of Distances in Tree

时间:2019-10-04 18:05:17      阅读:75      评论:0      收藏:0      [点我收藏+]

思路:

树形dp。

实现:

 1 class Solution
 2 {
 3 public:
 4     void dfs(int root, int p, vector<vector<int>>& G, vector<int>& cnt, vector<int>& res)
 5     {
 6         for (auto it: G[root])
 7         {
 8             if (it == p) continue;
 9             dfs(it, root, G, cnt, res);
10             cnt[root] += cnt[it];
11             res[root] += res[it] + cnt[it];
12         }
13         cnt[root]++;
14     }
15     void dfs2(int root, int p, vector<vector<int>>& G, vector<int>& cnt, vector<int>& res, int N)
16     {
17         for (auto it: G[root])
18         {
19             if (it == p) continue;
20             res[it] = res[root] - cnt[it] + N - cnt[it];
21             dfs2(it, root, G, cnt, res, N);
22         }
23     }
24     vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges)
25     {
26         vector<vector<int>> G(N, vector<int>());
27         for (auto it: edges)
28         {
29             int a = it[0], b = it[1];
30             G[a].push_back(b); G[b].push_back(a);
31         }
32         vector<int> cnt(N, 0), res(N, 0);
33         dfs(0, -1, G, cnt, res);
34         dfs2(0, -1, G, cnt, res, N);
35         return res;
36     }
37 }

leetcode834 Sum of Distances in Tree

原文:https://www.cnblogs.com/wangyiming/p/11622629.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!