Cod sursa(job #1148014)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 20 martie 2014 12:51:39
Problema Cerere Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.73 kb
#include <cstdio>
#include <cmath>
#include <cstring>

#define Nmax 100005

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

#define DIM 1000000
char buff[DIM];
int poz=DIM-1;

void citeste(int &numar)
{
     numar = 0;
     while (buff[poz] < '0' || buff[poz] > '9')
          if (++poz == DIM)
               fread(buff,1,DIM,stdin),poz=0;
     while ('0'<=buff[poz] && buff[poz]<='9')
     {
          numar = numar*10 + buff[poz] - '0';
          if (++poz == DIM)
               fread(buff,1,DIM,stdin),poz=0;
     }
}


void read()
{
    int a,b;
    citeste(N);
    for(int i = 1; i <= N; ++i)
        citeste(cere[i]);
    for(int i = 1; i < N; ++i)
    {
        citeste(a);citeste(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]];
}
int memo[Nmax];

void solve()
{
    memset(memo,-1,sizeof(memo));
    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 <= val)++put;
                --put;
                x = DP[put][x];
                val -= 1<<put;
            }
            if(memo[x] != -1)
            {
                total += memo[x];
                break;
            }
        }
        memo[i] = total;
        printf("%d ",total);
    }
}

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

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

    return 0;
}