Cod sursa(job #3342512)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 24 februarie 2026 15:35:26
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.03 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5;

int n, ind;
int a[NMAX + 1];
int dp[NMAX + 1];
vector<int> g[NMAX + 1];
int st[NMAX + 1];
int parent[NMAX + 1];

void DFS(int node, int dad = 0) {
    if(a[node]) {
        dp[node] = dp[st[ind - a[node] + 1]] + 1;
    }
    st[++ind] = node;

    for(int next_node : g[node]) {
        if(next_node != dad) {
            DFS(next_node, node);
        }
    }

    ind--;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    fin >> n;
    for(int i = 1; i <= n; i++) {
        fin >> a[i];
    }
    for(int i = 1; i <= n - 1; i++) {
        int a, b;
        fin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
        parent[b] = a;
    }

    int root = 1;
    while(parent[root]) {
        root = parent[root];
    }
    DFS(root);
    for(int i = 1; i <= n; i++) {
        fout << dp[i] << ' ';
    }
    return 0;
}