读不懂题的树

oddpointa / 2023-08-30 / 原文

A - TreeScript

vjudge上面看到的比较简洁的写法

据说是一种树形dp

转移方程就是父亲节点的寄存器数量等于max(最大子树的寄存器数量,次大子树的寄存器数量+1)

脑子转不过来不想转

//一种vector用法
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;

vector<int> G[N];

int dfs(int u, int fa) {
   if (G[u].size() == 0) {
   	return 0;
   }
   vector<int> vec;//
   for (auto v : G[u]) {
   	if (v == fa)
   		continue;
   	vec.push_back(dfs(v, u));
   }
   sort(vec.begin(), vec.end());
   //cout << "v:" << u << " fa:" << fa << endl;
   //for (auto x : vec) {
   //	cout << x << " ";
   //}
   //cout << endl;
   if (vec.size() == 1) {
   	return vec[0];
   } else {
   	return max(vec[vec.size() - 2] + 1, vec[vec.size() - 1]);
   }
}

void solve() {
   int n, rt = 1;
   cin >> n;
   for (int i = 1; i <= n; i++) {
   	G[i].clear();
   }
   for (int i = 1, x; i <= n; i++) {
   	cin >> x;
   	if (x == 0) {
   		rt = i;
   	}
   	G[x].push_back(i);
   }
   cout << dfs(rt, 0) + 1 << endl;
}

int main() {
   ios::sync_with_stdio(0);
   cin.tie(0);
   cout.tie(0);
   int T;
   cin >> T;
   while (T--) {
   	solve();
   }
   return 0;
}