zoukankan      html  css  js  c++  java
  • leetcode834 Sum of Distances in Tree

    思路:

    树形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 }
  • 相关阅读:
    Pandas对于CSV的简单操作
    前端之BOM和DOM
    前端之JavaScript
    前端之CSS初识
    定时ping取返回值并绘图
    etree不存在解决方法
    内置方法练习(一)
    pip使用
    python变量、变量属性
    python 爬取段子网段子写入文件
  • 原文地址:https://www.cnblogs.com/wangyiming/p/11622629.html
Copyright © 2011-2022 走看看