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;
typedef long long ll;
const int N = 100010, INF = 1000000000;
vector<int> adj[N];
vector<int> mn, dist;
vector<pair<int, bool>> order;
int lg = 1;
void dfs(int n, int par){
sort(adj[n].begin(), adj[n].end(), [](int a, int b){return mn[a] < mn[b];});
if(par != -1)dist[n] = dist[par] + 1;
lg = max(lg, dist[n]);
for(int c : adj[n]){
if(c != par){
dfs(c, n);
}
}
order.emplace_back(n, false);
}
void init(int n, int par){
mn[n] = n;
for(int c : adj[n]){
if(c != par){
init(c, n);
mn[n] = min(mn[n], mn[c]);
}
}
}
int main(){
ios_base :: sync_with_stdio(false);
cin.tie(nullptr);
int n, m, root;
cin >> n >> m;
vector<int> p(n);
for(int i=0; i<n; i++){
cin >> p[i];
--p[i];
if(p[i] != -1){
adj[i].push_back(p[i]);
adj[p[i]].push_back(i);
}else root = i;
}
vector<int> id(n);
dist.resize(n, INF);
mn.resize(n, INF);
dist[root] = 0;
init(root, -1);
dfs(root, -1);
for(int i=0; i<n; i++)id[order[i].first] = i;
set<int> tofill;
for(int i=0; i<n; i++)tofill.insert(i);
lg = 32 - __builtin_clz(lg + 1);
vector<int> B[lg];
{
B[0].resize(n);
B[0][root] = root;
for(int i=0; i<n; i++)if(p[i] != -1)B[0][i] = p[i];
for(int c=1; c<lg; c++){
B[c].resize(n);
for(int i=0; i<n; i++){
B[c][i] = B[c-1][B[c-1][i]];
}
}
}
p[root] = root;
for(int i=0; i<m; i++){
int t, x;
cin >> t >> x;
if(t & 1){
vector<int> tem;
auto it = tofill.begin();
while(x--){
assert(it != tofill.end());
order[*it].second = true;
tem.push_back(*it);
++it;
}
cout << order[tem.back()].first + 1 << '\n';
for(int &c : tem)tofill.erase(c);
}else {
--x;
int y = x;
// while(y != p[y] && order[id[p[y]]].second)y = p[y];
for(int i = lg - 1; i>=0; i--){
if(order[id[B[i][y]]].second)y = B[i][y];
}
// cout << y << '\n';
order[id[y]].second = false;
tofill.insert(id[y]);
cout << dist[x] - dist[y] << '\n';
}
}
return 0;
}
Compilation message (stderr)
ballmachine.cpp: In function 'int main()':
ballmachine.cpp:77:13: warning: 'root' may be used uninitialized in this function [-Wmaybe-uninitialized]
77 | p[root] = 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... |