Pagini recente » Cod sursa (job #1649128) | Cod sursa (job #2435612) | Cod sursa (job #2021541) | Cod sursa (job #2107300) | Cod sursa (job #974429)
Cod sursa(job #974429)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
#define u unsigned int
#define f first
#define s second
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int N = 250010;
const int M = 300010;
const int LG = 19;
int n, m, top, i, st[LG];
typedef pair <int, int> query;
vector <int> a[N], sol(M, 0), vfst;
vector <query> q[N];
vector <bool> viz(N);
stack <int> stck;
void dfs(const int start)
{
int top = 1;
stck.push(start);
while(!stck.empty())
{
bool ok = 0;
int x = stck.top();
st[top] = x;
for(u i=0; i<q[x].size(); i++)
{
int nrq = q[x][i].f, str = q[x][i].s;
if(top > str) sol[nrq] = st[top - str];
else sol[nrq] = 0;
}
for(u i=0; i<a[x].size(); i++)
if(!viz[a[x][i]])
{
viz[a[x][i]] = 1;
ok = 1;
stck.push(a[x][i]);
++top;
break;
}
if(!ok) stck.pop(), 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;
}