题解:AT_agc009_b [AGC009B] Tournament

· · 题解

比较好想的树形 dp。

输者向打败他的人连边,形成了一棵有根树。设 f_u 表示 u 要赢所需的最小场数。u 可以以任意顺序击败它的儿子,当加入一个儿子 v 时有:

f_u\leftarrow\max(f_u,f_v)+1

贪心,将所有儿子按照 f 从小到大排序即可。

#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int n, f[N];
vector<int> G[N];
void dfs(int u) {
    for (int v : G[u]) dfs(v);
    sort(G[u].begin(), G[u].end(), [](int x, int y) { return f[x] < f[y]; });
    for (int v : G[u]) f[u] = max(f[u], f[v]) + 1;
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i = 2, f; i <= n; i++) cin >> f, G[f].emplace_back(i);
    dfs(1), cout << f[1];
}