1. 程式人生 > 其它 >【leetcode】圖演算法 834. Sum of Distances in Tree

【leetcode】圖演算法 834. Sum of Distances in Tree

  There is an undirected connected tree withnnodes labeled from0ton - 1andn - 1edges.You are given the integernand the arrayedgeswhereedges[i] = [ai, bi]indicates that there is an edge between nodesaiandbiin the tree.Return an arrayanswerof lengthnwhereanswer[i]is the sum of the distances between theithnode in the tree 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: The tree is shown above. 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.   
class Solution {
public:
    vector<int> sumOfDistancesInTree(int
n, vector<vector<int>>& edges) { //好久沒做和圖論相關的題目了 圖論的題目 dfs bfs? //連結圖連結串列 vector<int> res(n),count(n); vector<vector<int>> tree(n); for(auto &edge:edges) { tree[edge[0]].push_back(edge[1]); tree[edge[
1]].push_back(edge[0]); } helper(tree,0,-1,count,res); helper2(tree,0,-1,count,res); return res; } void helper(vector<vector<int>> &tree,int cur,int pre,vector<int>&count,vector<int>& res) {
for(int i:tree[cur]) { if(i==pre) continue; helper(tree,i,cur,count,res); count[cur]+=count[i];//這個統計更新的邏輯 還是不懂。。 res[cur]+=res[i]+count[i]; } ++count[cur]; } void helper2(vector<vector<int>> &tree,int cur,int pre,vector<int>&count,vector<int>& res) { for(int i:tree[cur]) { if(i==pre) continue; res[i]=res[cur]-count[i]+count.size()-count[i]; helper2(tree, i, cur, count, res); } } };