Cod sursa(job #2296287)

Utilizator ilie0712Botosan Ilie ilie0712 Data 4 decembrie 2018 16:34:56
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.82 kb
//
//#include <fstream>
//
//#include <iostream>
//#include <algorithm>
//#include <vector>
//
//
//using namespace std;
//
//
//ifstream in("cerere.in");
//ofstream out("cerere.out");
//
//const int N=100003;
//
//vector <int> a[N];
//
//int n,contor,v[N],cost[N],d[N];
//
//void dfs(int x, int niv)
//{
//    d[niv]=x;
//    cost[x]=1+cost[d[niv-v[x]]];
//    for(auto y:a[x])
//            dfs(y,niv+1);
//}
//
//int main()
//{
//    in>>n;
//    for(int i=1; i<=n; ++i) in>>v[i];
//    int x,y;
//    while(in>>x>>y)
//    {
//        a[x].push_back(y);
//        a[y].push_back(x);
//    }
//    dfs(1,1);
//    for(int i=1; i<=n; ++i) out<<cost[i]-1<<" ";
//    return 0;
//}

#include <bits/stdc++.h>



using namespace std;



// ifstream in("cerere.in");

// ofstream out("cerere.out");



const int Nmax = 1e5 + 10;



int v[Nmax];

bool viz[Nmax];

vector< int > G[Nmax], s;



void DFS(int node) {

    viz[node] = true;

    s.push_back(node);



    for(auto vecin: G[node]) {

        if(!viz[vecin]) {

            if(v[vecin] != 0) {

                v[vecin] = v[s[(int)s.size() - v[vecin]]] + 1;

            }



            DFS(vecin);

        }

    }



    s.pop_back();

}



int main() {

    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);

    freopen("cerere.in", "r", stdin);

    freopen("cerere.out", "w", stdout);



    int n; cin >> n;



    for(int i = 1; i <= n; ++i) {

        cin >> v[i];

    }



    vector< bool > isRoot(n + 1, true);

    for(int i = 1; i < n; ++i) {

        int a, b; cin >> a >> b;

        G[a].push_back(b);

        isRoot[b] = false;

    }



    for(int i = 1; i <= n; ++i) {

        if(isRoot[i]) {

            DFS(i);

            break;

        }

    }



    for(int i = 1; i <= n; ++i) {

        cout << v[i] << " ";

    }



    // in.close(); out.close();



    return 0;

}