Cod sursa(job #780828)

Utilizator ionut_blesneagIonut Blesneag ionut_blesneag Data 22 august 2012 01:06:52
Problema Cerere Scor 85
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.84 kb
#include<fstream>
using namespace std;
ifstream f("cerere.in");
ofstream g("cerere.out");

int n,i,j,k,a,b,q[100001],lg[100001],incrm,imax,ancestor;
int m[20][100001],ans[100001];

int main()
{f>>n;
for(i=1; i<=n; i++)
  f>>q[i];
for(i=1; i<=n-1; i++)
  {f>>a>>b;
   m[0][b]=a;} 
incrm=1;
i=0;
while(incrm)
 {i++;
  incrm=0;
  for(j=1; j<=n; j++) 
    {m[i][j]=m[i-1][m[i-1][j]];
     if(m[i][j]!=0)
       incrm=1;}
  }        
imax=i-1;    

for(i=2; i<=n; i++)
 lg[i]=lg[i/2]+1;

/*for(i=0; i<=imax; i++)
 {for(j=1; j<=n; j++) 
  g<<m[i][j]<<" ";
 g<<endl;} */


for(k=1; k<=n; k++) 
{j=k; // ancestor=q[k];
while(q[j]!=0)
{ancestor=q[j];
ans[k]++;
while(ancestor)
{i=lg[ancestor];
j=m[i][j];
ancestor=ancestor-(1<<i);}
}
}

for(k=1; k<=n; k++)
 g<<ans[k]<<" ";      
f.close();
g.close();
return 0;}