LC5908-统计最高分的节点数目


5908. 统计最高分的节点数目

dfs

using ll = long long;
class Solution {
public:
    ll n, res, ans;
    ll dfs(vector>& G, int root){
        ll cnt = 1,tmp = 1;
        for(auto & e : G[root]){
            ll c = dfs(G,e);
            cnt += c;tmp *= c;
        }
        tmp *= 1ll * max(n - cnt, 1ll);
        if(tmp > res)res = tmp, ans = 1;
        else if(tmp == res) ans ++;
        return cnt;
    }
    int countHighestScoreNodes(vector& parents) {
        res = ans = 0;n = parents.size();
        vector>G(n);
        for(int i = 1; i < parents.size(); ++i)G[parents[i]].push_back(i);
        dfs(G,0);
        return ans;
    }
};

相关