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;
const int maxN = 1e5 + 5;
vector<int> adj[maxN];
int mn[maxN], depth[maxN], order[maxN], save[maxN], par[17][maxN];
int tick = 0, timeDfs = 0;
bool added[maxN];
void dfs(int u) {
mn[u] = u;
for (auto v: adj[u]) {
par[0][v] = u;
depth[v] = depth[u] + 1;
dfs(v);
mn[u] = min(mn[u], mn[v]);
}
}
void dfs_order(int u) {
for (auto v: adj[u]) {
dfs_order(v);
}
order[++tick] = u;
}
bool cmp (int u, int v) {
return mn[u] < mn[v];
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n, q, root = 0;
cin >> n >> q;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
if (x == 0) root = i;
else adj[x].push_back(i);
}
depth[root] = 1;
dfs(root);
for (int i = 1; i <= n; i++)
if (adj[i].size() > 0) sort(adj[i].begin(), adj[i].end(), cmp);
dfs_order(root);
stack<int> pq;
for (int i = n; i >= 1; i--)
pq.push(i);
for (int i = 1; i <= n; i++)
save[order[i]] = i;
for (int k = 1; k <= 16; k++) {
for (int i = 1; i <= n; i++)
par[k][i] = par[k - 1][par[k - 1][i]];
}
while (q--) {
int type;
cin >> type;
if (type == 1) {
int k;
cin >> k;
int ans = 0;
while (k--) {
int ord = pq.top(), u = order[ord];
pq.pop();
added[u] = true;
ans = u;
}
cout << ans << '\n';
}
else {
int u; cin >> u; int ans = u;
for (int k = 16; k >= 0; k--) {
if (par[k][ans] == 0) continue;
int v = par[k][ans];
if (added[v]) ans = v;
}
cout << depth[u] - depth[ans] << '\n';
pq.push(save[ans]);
added[ans] = false;
}
}
return 0;
}
# | 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... |