Skip to content

Commit 57d3cf8

Browse files
Add files via upload
1 parent c38fbb1 commit 57d3cf8

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#pragma GCC optimize("Ofast")
2+
#pragma GCC optimize("unroll-loops")
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
typedef long long ll;
7+
typedef vector<int> vi;
8+
#define fast_cin() \
9+
ios_base::sync_with_stdio(false); \
10+
cin.tie(NULL); \
11+
cout.tie(NULL);
12+
13+
int n;
14+
vector<vector<int>> children;
15+
vector<int> memo;
16+
17+
void dfs(int u) {
18+
for (auto v : children[u]) {
19+
dfs(v);
20+
}
21+
22+
priority_queue<int, vector<int>, greater<int>> pq; // min heap
23+
int count = 0;
24+
for (auto v : children[u]) {
25+
pq.push(memo[v]);
26+
count++;
27+
}
28+
29+
while (count > 2) {
30+
int least = pq.top();
31+
pq.pop();
32+
int second_least = pq.top();
33+
pq.pop();
34+
pq.emplace(max(least, second_least) + 1);
35+
count--;
36+
}
37+
38+
if (count == 0) {
39+
memo[u] = 0;
40+
} else if (count == 1) {
41+
memo[u] = pq.top() + 1;
42+
} else {
43+
pq.pop();
44+
memo[u] = pq.top() + 1;
45+
}
46+
}
47+
int main() {
48+
fast_cin();
49+
int tc;
50+
cin >> tc;
51+
while (tc--) {
52+
cin >> n;
53+
children.assign(n, vector<int>());
54+
for (int i = 1; i < n; i++) {
55+
int p;
56+
cin >> p;
57+
p--;
58+
children[p].push_back(i);
59+
}
60+
61+
memo.assign(n, -1);
62+
dfs(0);
63+
cout << memo[0] << endl;
64+
}
65+
66+
return 0;
67+
}

0 commit comments

Comments
 (0)