This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define pii pair<int, int>
#define fr first
#define se second
const int MAXN = 1e5 + 10;
const int MAXLOG = 18;
int n, q;
int dad[MAXN];
int binl[MAXLOG + 5][MAXN];
int minin[MAXN];
int ocupado[MAXN];
int h[MAXN];
vector<int> adj[MAXN];
int t = 0;
int order[MAXN];
void dfs(int node) {
if (adj[node].size() == 0) minin[node] = node;
else minin[node] = 0x3f3f3f3f;
for (auto u : adj[node]) {
h[u] = h[node] + 1;
dfs(u);
minin[node] = min(minin[node], minin[u]);
}
}
void calcOrder(int node) {
for (auto u : adj[node]) calcOrder(u);
order[node] = ++t;
}
int lastB(int x) {
for (int i = MAXLOG - 1; i >= 0; i--) {
int maybe = binl[i][x];
if (ocupado[maybe]) x = maybe;
}
return x;
}
bool comp(int a, int b) {
return minin[a] < minin[b];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> q;
int root;
for (int i = 1; i <= n; i++) {
cin >> dad[i];
adj[dad[i]].push_back(i);
if (dad[i] == 0) root = i;
}
dfs(root);
for (int i = 1; i <= n; i++) {
//cout << minin[i] << "\n";
sort(adj[i].begin(), adj[i].end(), comp);
}
//cout << "oi\n";
calcOrder(root);
priority_queue<pii> ops;
for (int i = 1; i <= n; i++) {
//cout << order[i] << "\n";
ops.push({-order[i], i});
}
// lets calc binlift lesgooo
for (int i = 1; i <= n; i++) {
binl[0][i] = dad[i];
}
for (int j = 1; j < MAXLOG; j++) {
for (int i = 1; i <= n; i++) {
binl[j][i] = binl[j - 1][binl[j - 1][i]];
}
}
// done bitches
//cout << "ok\n";
int lst = 0;
while (q--) {
int t, x;
cin >> t >> x;
if (t == 2) {
// beautiful
int k = lastB(x);
cout << h[x] - h[k] << "\n";
ocupado[k] = 0;
ops.push({-order[k], k});
continue;
}
// insert x into 1
while (x--) {
int add = ops.top().se;
//cout << "put " << add << "\n";
ops.pop();
lst = add;
ocupado[add] = 1;
}
cout << lst << "\n";
}
}
Compilation message (stderr)
ballmachine.cpp: In function 'int main()':
ballmachine.cpp:64:14: warning: 'root' may be used uninitialized in this function [-Wmaybe-uninitialized]
64 | calcOrder(root);
| ~~~~~~~~~^~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |