Pagini recente » Cod sursa (job #1000040) | Cod sursa (job #2486258) | Cod sursa (job #1531754) | Cod sursa (job #1666268) | Cod sursa (job #1850431)
#include <stdio.h>
const int nmax=250001;
const int mmax=300001;
struct question
{
int p, ind, next;
};
int head[nmax];
question l[mmax];
void push(int p1, int p2, int ind, int pos)
{
l[pos].p=p2;
l[pos].ind=ind;
l[pos].next=head[p1];
head[p1]=pos;
}
struct edge
{
int node, next;
};
int boss[nmax];
edge tree[nmax];
void push2(int p1, int p2, int pos)
{
tree[pos].node=p2;
tree[pos].next=boss[p1];
boss[p1]=pos;
}
int ans[mmax];
int marked[nmax];
int stack[nmax];
int sz;
void dfs(int node)
{
int i,c;
c=node;
++sz;
stack[sz]=c;
marked[c]=1;
i=head[c];
while (i)
{
int aux=sz-l[i].p;
if (aux > 0)
ans[l[i].ind]=stack[sz-l[i].p];
else
ans[l[i].ind]=0;
i=l[i].next;
}
i=boss[c];
while (i)
{
if (!marked[tree[i].node])
{
dfs(tree[i].node);
}
i=tree[i].next;
}
sz--;
}
int main()
{
FILE *f;
int n,m,p,q,x,i;
f=fopen("stramosi.in","r");
fscanf(f,"%d%d",&n,&m);
for (i=1; i<=n; i++)
{
fscanf(f,"%d",&x);
push2(x,i,i);
}
for (i=1; i<=m; i++)
{
fscanf(f,"%d%d",&q,&p);
push(q,p,i,i);
}
fclose(f);
for(i=1; i<=n; i++)
if (!marked[i])
dfs(i);
f=fopen("stramosi.out","w");
for (i=1; i<=m; i++)
fprintf(f,"%d\n",ans[i]);
fclose(f);
}