Pagini recente » Cod sursa (job #1075260) | Cod sursa (job #458653) | Cod sursa (job #410790) | Cod sursa (job #2599152) | Cod sursa (job #66598)
Cod sursa(job #66598)
#include<stdio.h>
int a[31][100005], v[100005], pt[30], p, q, y, k[100005];
int poz (int p, int q){
int li=0, ls=30, x;
while (li<=ls){
x=(li+ls)/2;
if (pt[x]<q&&pt[x+1]>=q)
return x;
else
if (pt[x]<q)
li=x+1;
else
ls=x-1;
}
return -1;
}
int caut(){
while (q!=1){
y=poz(p,q);
p=a[y][p];
q=q-pt[y];
}
return v[p];
}
int main()
{
freopen("cerere.in","r",stdin);
freopen("cerere.out","w",stdout);
int n, i, j, a1, b, nr;
scanf("%d",&n);
for (i=1;i<=n;i++)
scanf("%d",&k[i]);
for (i=1;i<n;i++){
scanf("%d%d",&a1,&b);
v[b]=a1;
}
for (i=1;i<n;i++)
a[0][i]=v[i];
pt[0]=1;
for (i=1;i<=30;i++){
for (j=1;j<n;j++)
a[i][j]=a[i-1][a[i-1][j]];
pt[i]=2*pt[i-1];
}
for (i=1;i<=n;i++){
nr=0;
q=k[i];
p=i;
while (q){
nr++;
q=k[caut()];
p=v[q];
}
printf("%d ",nr);
}
fclose(stdin);
fclose(stdout);
return 0;
}