Pagini recente » Cod sursa (job #759029) | Cod sursa (job #3123332) | Cod sursa (job #2300025) | Cod sursa (job #1590676) | Cod sursa (job #2132332)
#include <bits/stdc++.h>
#define INFILE "stramosi.in"
#define OUTFILE "stramosi.out"
#define timp first
#define nod second
using namespace std;
typedef pair<int,int> timpNod;
ifstream in(INFILE);
ofstream out(OUTFILE);
struct Graph{
vector<vector<int>> Adj;
int N;
void Init(int N){
this->N=N;
Adj.resize(N+1);
}
void Add(int x,int y){
Adj[x].push_back(y);
}
}G;
int N,M;
vector<vector<timpNod> > nivel;
map<int,int> nivelul;
map<int,int> timpul;
void Read(){
in>>N>>M;
G.Init(N);
nivel.resize(N+1);
for(int i=1;i<=N;i++){
int x;
in>>x;
G.Add(x,i);
}
}
void DFS(int x,int&timp,int niv){
timp++;
nivel[niv].push_back(make_pair(timp,x));
nivelul[x]=niv;
timpul[x]=timp;
for(auto y:G.Adj[x]){
DFS(y,timp,niv+1);
}
}
void Prelucrare(){
int tmp=0;
DFS(0,tmp,0);
for(int i=0;i<nivel.size();i++){
sort(nivel[i].begin(),nivel[i].end());
}
}
int BQuerry(int val,int niv){
int low=0;
int high=nivel[niv].size();
int rasp=0;
while(low!=high){
int mid=(low+high)/2;
if(val>=nivel[niv][mid].timp){
low=mid+1;
}
else{
high=mid;
}
}
return high-1;
}
int main()
{
Read();
Prelucrare();
for(int i=1;i<=M;i++){
int Q,P;
in>>Q>>P;
int nv=nivelul[Q];
int val=timpul[Q];
int sc=nv-P;
if(sc<0)
sc=0;
int j=BQuerry(val,sc);
out<<nivel[sc][j].nod<<"\n";
}
return 0;
}