Cod sursa(job #2147396)

Utilizator CryshanaGanea Carina Cryshana Data 28 februarie 2018 18:26:06
Problema Cerere Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin  ("cerere.in" );
ofstream fout ("cerere.out");

const int N = 100001;
int a[N], d[N];
vector <int> o[N];
int  n;
int v[N], c,t, rez[N], mem[N];
bool m[N];

void citire()
{
    fin >> n;
    int x, y;
    for ( int i = 1 ; i <= n ; i++ )
    {
        fin >> v[i];
        if ( v[i] == 0 )
        mem[c++] = i;
    }
    for ( int i = 1 ; i < n ; i++ )
    {
        fin >> x >> y;
        a[y] = x;
        o[x].push_back(y);
    }
    while ( a[mem[t]] != 0 && t < c)
    {
        t++;
    }
    t = mem[t];
}

void dfs ( int x , int nivel )
{
    m[x] = 1;
    d[nivel] = x;
    rez[x] = rez[ d[nivel - v[x]]] + 1;
    int y;
    for ( int i = 0 ; i < o[x].size() ; i++ )
    {
        y = o[x][i];
        if ( !m[y] )
        {
            if ( a[x] != y )
            {
                dfs(y, nivel+1);
            }
        }
    }

}

int main()
{
    citire();
    dfs(t,1);
    for ( int i = 1 ; i <= n ; i++ )
    {
        fout << rez[i] - 1 << " ";
    }
    return 0;
}