Pagini recente » Cod sursa (job #1840913) | Cod sursa (job #2305621) | Cod sursa (job #2599302) | Cod sursa (job #2332480) | Cod sursa (job #974416)
Cod sursa(job #974416)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
#define u unsigned int
#define f first
#define s second
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int N = 350010;
const int M = 450010;
int n, m, top, i, st[M];
typedef pair <int, int> query;
vector <int> a[N], sol(M, 0), vfst;
vector <query> q[N];
void dfs(const int x)
{
st[++top] = x;
for(i=0; i<q[x].size(); i++)
if(top > q[x][i].s) sol[q[x][i].f] = st[top - q[x][i].s];
else sol[q[x][i].f] = 0;
for(i=0; i<a[x].size(); i++)
dfs(a[x][i]);
--top;
}
int main()
{
fin>>n>>m;
int x, y;
for(int i=1; i<=n; i++)
{
fin>>x;
if(x) a[x].push_back(i);
else vfst.push_back(i);
}
for(int i=1; i<=m; i++)
{
fin>>x>>y;
q[x].push_back(query(i, y));
}
for(u i = 0; i < vfst.size(); i++)
dfs(vfst[i]);
for(int i=1; i<=m; i++)
fout<<sol[i]<<'\n';
return 0;
}