Pagini recente » Cod sursa (job #2779037) | Cod sursa (job #2282647) | Cod sursa (job #1792550) | Cod sursa (job #704834) | Cod sursa (job #66596)
Cod sursa(job #66596)
#include<stdio.h>
int a[21][1000005], v[100005], pt[20], p, q, y, k[100005];
int poz (int p, int q){
int li=0, ls=20, 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<=20;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;
}