LeetCode 834. 树中距离之和

LeetCode 834. 树中距离之和_第1张图片

简单换根DP

其实就是看好变化量,然后让父亲更新儿子就好了~

上图2当根节点的时候,ans[2] = ans[0] -sz[2]+n-sz[2];

class Solution {
public:
    vector sumOfDistancesInTree(int n, vector>& edges) {
        vector>g(n);
        for(auto &edge:edges){
            int a = edge[0],b = edge[1];
            g[a].push_back(b),g[b].push_back(a);
        }
        using ll = long long;
        vectorans(n);
        vectorsz(n+10);
        functiondfs=[&](int u,int father,int dist){
            sz[u] = 1;
            ans[0]+=dist;
            for(auto &v:g[u]){
                if(v==father)continue;
                dfs(v,u,dist+1);
                sz[u]+=sz[v];
            }
        };

        functiondown=[&](int u,int father){
            for(auto &v:g[u]){
                if(v==father)continue;
                ans[v] = ans[u]-sz[v]+n-sz[v];
                down(v,u);
            }
        };
        dfs(0,-1,0);
        down(0,-1);
        return ans;


    }
};

你可能感兴趣的:(DP,leetcode,算法,职场和发展,c++,蓝桥杯,c语言)