Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
hackercup / 2021 /round3 /perf-ore-mance.cpp
wjomlex's picture
2021 Problems
d3f4f72 verified
raw
history blame
3.15 kB
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
const int LIM = 800002;
const int MAXK = 10;
int N, K;
vector<int> children[LIM];
// dp[i][j] = max # of guessable nodes only considering i's subtree,
// such that i's subtree size is j (with j capping out at K + 1)
int dp[LIM][MAXK + 2];
// dp2[s] = max # of guessable nodes only considering current node's subtree
// such that its subtree size is s (with s capping out at K + 1)
int dp2[MAXK + 2];
// dp3[a][b] = max # of guessable nodes only considering current node's subtree
// such that it has a children (with a capping out at K)
// one of which has subtree size 2 if and only if b = 1,
// and the rest of which have subtree sizes either 1 or > K
int dp3[MAXK + 1][2];
void rec(int i) {
// Recursively compute children's DP values.
for (int c : children[i]) {
rec(c);
}
// Use children's DP values.
memset(dp2, -1, sizeof dp2);
memset(dp3, -1, sizeof dp3);
dp2[1] = dp3[0][0] = 0;
for (int c : children[i]) {
// Assume no new guessable nodes.
for (int s1 = K + 1; s1 >= 1; s1--) {
int d1 = dp2[s1];
if (d1 >= 0) {
for (int s2 = 1; s2 <= K + 1; s2++) {
int d2 = dp[c][s2];
if (d2 >= 0) {
int s = min(K + 1, s1 + s2);
dp2[s] = max(dp2[s], d1 + d2);
}
}
}
}
// New guessable node, situation 1:
// - Node i has 1 child
// - That child's subtree size is > K (that child is guessable)
int d1 = dp[c][K + 1];
if (d1 >= 0) {
dp[i][K + 1] = max(dp[i][K + 1], d1 + 1);
}
// New guessable node, situation 2:
// - Node i has at least K children
// - One child's subtree size is exactly 2 (that child's single child is
// guessable)
// - Each other child's subtree size is either exactly 1, or > K
for (int a1 = K; a1 >= 0; a1--) {
for (int b1 : {1, 0}) {
d1 = dp3[a1][b1];
if (d1 >= 0) {
int a2 = min(K, a1 + 1);
int d2 = max(dp[c][1], dp[c][K + 1]);
if (d2 >= 0) {
dp3[a2][b1] = max(dp3[a2][b1], d1 + d2);
}
if (!b1 && (d2 = dp[c][2]) >= 0) {
dp3[a2][1] = max(dp3[a2][1], d1 + d2);
}
}
}
}
}
// Merge sub-DP results into main DP.
for (int s1 = 1; s1 <= K + 1; s1++) { // No new guessable nodes.
dp[i][s1] = max(dp[i][s1], dp2[s1]);
}
int d1 = dp3[K][1];
if (d1 >= 0) { // New guessable node, situation 2.
dp[i][K + 1] = max(dp[i][K + 1], d1 + 1);
}
}
int solve() {
for (int i = 0; i < N; i++) {
children[i].clear();
}
// Input.
cin >> N >> K;
for (int i = 1; i < N; i++) {
int p;
cin >> p;
children[p - 1].push_back(i);
}
// Tree DP.
memset(dp, -1, sizeof(dp[0]) * N);
rec(0);
// Compute answer.
int ans = 0;
for (int i = 1; i <= K + 1; i++) {
ans = max(ans, dp[0][i]);
}
return ans;
}
int main() {
int T;
cin >> T;
for (int t = 1; t <= T; t++) {
cout << "Case #" << t << ": " << solve() << endl;
}
return 0;
}