834. Sum of Distances in Tree(Leetcode每日一题-2020.10.06)--抄答案

    科技2025-01-16  8

    Problem

    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.

    Note: 1 <= N <= 10000

    Example

    Solution

    class Solution { public: unordered_map<int, vector <int>> graph;//图 unordered_map<int, int> chs; //节点包含是子节点数(不包括自身) //计算每个节点的chs值 void help(int N,int p) { int r = 0; for (auto& e : graph[N]) { if (p == e) continue; help(e, N); r += (1 + chs[e]); } chs[N] = r; return ; } //计算所有结点到root结点距离之和sum,在样例中是8,我们需要拿这个值去递推计算其子结点的答案即可 int fun(int N, int p) { int sum = 0; for (auto& e : graph[N]) { if (p == e) continue; sum+=(fun(e, N)+chs[e]); sum++; } return sum; } vector<int> ret; int totalNodes = 0; //自上而下递推计算ret值,其实就是利用父结点的答案+ 多少 - 多少 void dfs(int N,int p) { for (auto& e : graph[N]) { if (p!=-1) { ret[N] = ( ret[p] - chs[N] + (totalNodes-(chs[N]+1+1))); } if (p == e) continue; dfs(e, N); } } vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) { if (N == 1) { return { 0 }; } ret = vector<int>(N, 0); totalNodes = N; for (auto& e : edges) { graph[e[0]].push_back(e[1]); graph[e[1]].push_back(e[0]); } help(0,-1); int disRoot = fun(0, -1); ret[0] = disRoot; dfs(0, -1); return ret; } //https://leetcode-cn.com/problems/sum-of-distances-in-tree/solution/shou-hua-tu-jie-shu-zhong-ju-chi-zhi-he-shu-xing-d/ };
    Processed: 0.009, SQL: 8