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 ll long long
#define db double
#define pairll pair<ll,ll>
#define lpairll pair<ll,pairll>
#define repp(i,a,b) for (ll i = a; i <= b; i++)
#define repz(i,a,b) for (ll i = a; i < b; i++)
#define repm(i,a,b) for (ll i = a; i >= b; i--)
#define fr first
#define sc second
#define mp make_pair
#define pb push_back
const ll N = 2e5+5, MOD = 1e9+7, LOG = 20;
ll tc = 1, n, m, ar[N], br[N], used[N];
ll x, y, k, cur = 0;
string s, s1, s2, ye = "YES", no = "NO";
ll ord[N], root, nx[N][LOG+5], dlm[N];
vector<ll> ed[N];
void buildord(ll idx){
  for (auto i : ed[idx]){
    dlm[i] = dlm[idx]+1;
    buildord(i);
  }
  cur++;
  ord[idx] = cur;
}
void buildlift(){
  nx[root][0] = 0;
  repp(bt,1,LOG){
    repp(i,1,n){
      nx[i][bt] = nx[nx[i][bt-1]][bt-1];
    }
  }
}
void input(){
  cin >> n >> m;
  repp(i,1,n){
    cin >> ar[i];
    if (ar[i] == 0){
      root = i;
    }
    else{
      ed[ar[i]].pb(i);
      nx[i][0] = ar[i];
    }
  }
}
void solve(){
  repp(i,1,n){
    sort(ed[i].begin(),ed[i].end());
  }
  buildord(root);
  buildlift();
  priority_queue<pairll, vector<pairll>, greater<pairll> > pq;
  repp(i,1,n){
    pq.push(mp(ord[i],i));
  }
  while(m--){
    cin >> x >> y;
    if (x == 1){
      ll lst;
      while(y--){
        pairll a = pq.top();
        pq.pop();
        used[a.sc] = 1;
        lst = a.sc;
      }
      cout << lst << "\n";
    }
    else if(x == 2){
      ll dis = 0, ori = y;
      repm(bt,LOG,0){
        if (used[nx[y][bt]]){
          dis += (1<<bt);
          y = nx[y][bt];
        }
      }
      used[y] = 0;
      pq.push(mp(ord[y],y));
      cout << dlm[ori]-dlm[y] << "\n";
    }
  }
}
int main(){
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  //cin >> tc;
  while(tc--){
    input();
    solve();
  }
}
| # | 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... |