This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/*
Code by @marlov
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <utility>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <iterator>
using namespace std;
typedef long long ll;
typedef pair<int,int> pi;
#define maxN 100005
int N,Q;
int bl[maxN][16];
bool hasB[maxN];
//tree setup
vector<int> adj[maxN];
int stmin[maxN];
int ordering[maxN];
bool cmp(int a,int b){
return stmin[a]<stmin[b];
}
void dfs1(int n,int p){
if(adj[n].size()==0){
stmin[n]=n;
return;
}
for(int a:adj[n]) if(a!=p){
dfs1(a,n);
}
sort(adj[n].begin(),adj[n].end(),cmp);
stmin[n]=stmin[adj[n].front()];
}
int cno=0;
void dfs2(int n,int p){
for(int a:adj[n]) if(n!=p){
dfs2(a,n);
}
ordering[cno]=n;
cno++;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>N>>Q;
int cnp;
bl[N][0]=N;
for(int i=0;i<N;i++){
cin>>cnp;
if(cnp==0){
bl[i][0]=N;
}else{
cnp--;
bl[i][0]=cnp;
adj[cnp].push_back(i);
}
//adj[i].push_back(cnp);
}
for(int j=1;j<16;j++){
for(int i=0;i<=N;i++){
bl[i][j]=bl[bl[i][j-1]][j-1];
}
}
//order-processing
dfs1(0,-1);
dfs2(0,-1);
int t,v;
for(int z=0;z<Q;z++){
cin>>t>>v;
if(t==1){
for(int i=0;i<N;i++){
if(hasB[ordering[i]]==false){
hasB[ordering[i]]=true;
v--;
}
if(v==0||i==N-1){
cout<<ordering[i]+1<<'\n';
break;
}
}
}else if(t==2){
v--;
int cn=v;
int tl=0;
for(int j=15;j>=0;j--){
while(bl[cn][j]!=N&&hasB[bl[cn][j]]==true){
cn=bl[cn][j];
tl+=(1<<j);
}
}
cout<<tl<<'\n';
hasB[cn]=false;
}
}
return 0;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1,n=0?)
* do smth instead of nothing and stay organized
*/
# | 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... |