Cod sursa(job #1147946)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 20 martie 2014 12:08:45
Problema Cerere Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.08 kb
#include <cstdio>
#include <cmath>

#define Nmax 100005

using namespace std;
int cere[Nmax],N;
int DP[18][Nmax];

void read()
{
    int a,b;
    scanf("%d",&N);
    for(int i = 1; i <= N; ++i) scanf("%d",&cere[i]);
    for(int i = 1; i < N; ++i)
    {
        scanf("%d%d",&a,&b);
        DP[0][b] = a;
    }
}

void precompute()
{
    int len = (int)log2(N);
    for(int i = 1; i <= len; ++i)
        for(int j = 1; j <= N; ++j)
            DP[i][j] = DP[i-1][DP[i-1][j]];
}

void solve()
{
    int x,total,put,val,i;
    for(i = 1; i <= N; ++i)
    {
        total = 0;
        put = 0;
        x = i;
        while(cere[x])
        {
            ++total;
            val = cere[x];
            while(val)
            {
                while(1<<(put+1) < val)++put;
                x = DP[put][x];
                val -= 1<<put;
            }
        }
        printf("%d ",total);
    }
}

int main()
{
    freopen("cerere.in","r",stdin);
    freopen("cerere.out","w",stdout);

    read();
    precompute();
    solve();

    return 0;
}