Pagini recente » Cod sursa (job #2560026) | Cod sursa (job #337820) | Cod sursa (job #2659942) | Cod sursa (job #1677039) | Cod sursa (job #174221)
Cod sursa(job #174221)
#include <fstream.h>
#include <algo.h>
#define SIZE 250000
ifstream f("stramosi.in");
ofstream g("stramosi.out");
struct tip{int lu;int id;};
int v[SIZE],l2[SIZE],o[SIZE],p[SIZE],k;
tip l[SIZE];
int n,m;
int comp(tip x,tip y)
{
if(x.lu<y.lu)return 1;
return 0;}
void DF(int x){int i;k++;o[x]=k;
for(i=1; i<=n; i++)
if(!l[i].lu)
if(v[i]==x)
{
l[i].lu=l[x].lu+1;l2[i]=l[i].lu;
DF(i);
}
}
int main(){f>>n>>m;int i;
for(i=1; i<=n; i++)f>>v[i];
for(i=1; i<=n; i++)l[i].id=i;
for(i=1; i<=n; i++)
if(!v[i]){l[i].lu=1;l2[i]=1;DF(i);}
sort(l+1,l+n+1,comp);
int gas,man,max2,max,man2,j;
for(i=1; i<=n; i++)if(!p[l[i].lu])p[l[i].lu]=i;
for(i=1; i<=m; i++){
int x,y;
f>>x>>y;
if(l2[x]-y<1)g<<0<<'\n';
else{max=0; max2=0; man=0;man2=0;
int le=l2[x]-y;
for(j=p[le]; (j<=p[le+1]-1)&&(o[man]<o[x]); j++){
if(o[l[j].id]>max){
max2=max;man2=man;man=l[j].id;max=o[l[j].id];}
}
if(!man2)g<<man<<'\n'; else{
if(o[man]>o[x])g<<man2<<'\n';else g<<man<<'\n';}
}
}
return 0;}