CF 2238 C. Village Guilds【 树上DP 】

· · 题解

原题链接:https://codeforces.com/contest/2238/problem/C

#include<bits/stdc++.h>
using namespace std;
using i64 = long long; 
using ui64 = unsigned long long;
#define int i64
#define sz(a) int((a).size())
#define pii pair<int, int>
#define pll pair<i64, i64>
#define all(a) (a).begin(), (a).end()
const int inf = (1 << 30);
const i64 INF = (1ll << 60);
const double PI = acos(-1);

/*
Good: 关键式子推的很快
Need to improve: 
没有很好的想清楚回溯过程中具体怎么更新 (其实完全没想到把最大逆深度传回去)
*/

void work(){
    int n;
    cin >> n;
    // vector<int> p(n);
    vector<vector<int>> g(n);
    for(int i = 1; i < n; ++i){
        int p;
        cin >> p;
        --p;
        g[p].push_back(i);
    }

    vector<i64> dp(n);
    auto dfs = [&](auto &&self, int x) -> int {
        i64 sum = 0;
        int mx1 = 0, mx2 = 0;
        for(auto v : g[x]){
            int d = self(self, v); // 自底向上,回溯过程中更新
            if(d > mx1){
                mx2 = mx1;
                mx1 = d;
            } else if(d > mx2){
                mx2 = d;
            }
            sum += dp[v];
        }
        dp[x] = 1 + sum + mx2; // 关键式子
        return mx1 + 1; // 回溯过程中,传递最大逆深度 (加上 x 自己)
    };

    dfs(dfs, 0);

    cout << dp[0] << '\n';
} 

signed main(){
    // if(ifstream("data.in")) freopen("data.in", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T = 1;
    cin >> T;
    while(T--) work();
    return 0;
}