Cod sursa(job #2283249)

Utilizator TooHappyMarchitan Teodor TooHappy Data 15 noiembrie 2018 11:40:49
Problema Cerere Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.46 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream in("cerere.in");
ofstream out("cerere.out");

vector< int > v, ans;
vector< bool > viz;
vector< vector < int > > G;

void DFS() {
    stack< int > s; s.push(1);

    while(!s.empty()) {
        int node = s.top();
        viz[node] = true;
        bool toEliminate = true;

        for(auto vecin: G[node]) {
            if(!viz[vecin]) {
                toEliminate = false;

                if(v[vecin] != 0) {
                    stack< int > temp;
                    for(int k = 1; k <= v[vecin]; ++k) {
                        temp.push(s.top()); s.pop();
                    }

                    v[vecin] = v[temp.top()] + 1;
                    while(!temp.empty()) {
                        s.push(temp.top()); temp.pop();
                    }
                }

                s.push(vecin);
                goto eliminateNode;
            }
        }

        eliminateNode:
        if(toEliminate) {
            s.pop();
        }
    }
}

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);
 
    int n; in >> n;

    v.resize(n + 1); viz.resize(n + 1, false); G.resize(n + 1, vector< int >());
    for(int i = 1; i <= n; ++i) {
        in >> v[i];
    }

    for(int i = 1; i < n; ++i) {
        int a, b; in >> a >> b;
        G[a].push_back(b);
    }

    DFS();

    for(int i = 1; i <= n; ++i) {
        out << v[i] << " ";
    }
    out << "\n";

    in.close(); out.close();
 
    return 0;
}