Pagini recente » Cod sursa (job #2315700) | Cod sursa (job #1876003) | Cod sursa (job #345327) | Cod sursa (job #2678411) | Cod sursa (job #2921670)
#include <bits/stdc++.h>
#define N_MAX 250005
#define M_MAX 300005
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
struct MS{
int node;
int ancestor;
int index;
int answer;
};
MS v[M_MAX];
vector <int> G[N_MAX];
bool vis[N_MAX], root[N_MAX];
int pos_in_lin[N_MAX], path[N_MAX], n, q, ind, iq = 1;
bool cmp_top (const MS &a, const MS &b){
return pos_in_lin[a.node] < pos_in_lin[b.node];
}
bool cmp_ind (const MS &a, const MS &b){
return a.index < b.index;
}
void erase_vis (){
int i;
for (i = 1; i <= n; i++)
vis[i] = false;
ind = 0;
}
void DFS_lin (int node){
vis[node] = true;
pos_in_lin[node] = ind++;
for (auto it : G[node])
DFS_lin (it);
}
void DFS (int node){
vis[node] = true;
path[ind++] = node;
while (v[iq].node == node){
if (ind - v[iq].ancestor - 1 < 0)
v[iq].answer = 0;
else
v[iq].answer = path[ind - v[iq].ancestor - 1];
iq++;
}
for (auto it : G[node])
DFS (it);
ind--;
}
int main (){
int i, x;
fin >> n >> q;
for (i = 1; i <= n; i++){
fin >> x;
if (!x)
root[i] = true;
else
G[x].push_back (i);
}
for (i = 1; i <= q; i++){
fin >> v[i].node >> v[i].ancestor;
v[i].index = i;
}
for (i = 1; i <= n; i++)
if (root[i])
DFS_lin (i);
sort (v + 1, v + q + 1, cmp_top);
erase_vis ();
for (i = 1; i <= n; i++)
if (root[i])
DFS (i);
sort (v + 1, v + q + 1, cmp_ind);
for (i = 1; i <= q; i++)
fout << v[i].answer << "\n";
return 0;
}