Cod sursa(job #299203)

Utilizator rethosPaicu Alexandru rethos Data 6 aprilie 2009 17:04:14
Problema Cerere Scor 0
Compilator cpp Status done
Runda preONI Marime 1.07 kb
#include <stdio.h>
#define NM 100001
#define logNM 21
int n,logn;
int a[NM][logNM];
int k[NM];
int log[NM];
int t[NM];
int str[NM];
int calc(int);
int main()
{freopen("cerere.in","r",stdin);
 freopen("cerere.out","w",stdout);
 int i,j;
 scanf("%d",&n);
 int x,y;
 for (i=1;i<=n;i++)
	 {scanf("%d",&k[i]);
	 }
 for (i=1;i<n;i++)
	 {scanf("%d %d",&x,&y);
	  t[y]=x;
	 }
 logn=0;
 while ((1<<logn)<=n)
	 {logn++;
	 }
 logn--;
 for (i=1;i<=n;i++)
	 {a[i][0]=t[i];
	 }
 for (j=1;j<=logn;j++)
     for (i=1;i<=n;i++)
		 {a[i][j]=a[a[i][j-1]][j-1];
		 }
 for (i=1;i<=n;i++)
	 {if (k[i]==0)
		 {str[i]=i;
		  continue;
		 } 
	  str[i]=i;
	  while (k[i])
		  {x=0;
		   while ((1<<x)<=k[i])
			   {x++;
			   }
		   x--;
		   str[i]=a[str[i]][x];
		   k[i]-=(1<<x);
		  }
	 }
 for (i=1;i<=n;i++)
	 {k[i]=-1;
	 }
 for (i=1;i<=n;i++)
	 {if (k[i]==-1)
		 {k[i]=calc(i);
		 }
	 }
 for (i=1;i<=n;i++)
	 printf("%d ",k[i]);
 return 0;
}
int calc(int x)
{if (str[x]==x) return 0;
 if (k[str[x]]==-1) calc(str[x]);
 return k[str[x]]+1;
}