Cod sursa(job #2907011)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 28 mai 2022 14:17:42
Problema Cerere Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.02 kb
/// [A][M][C][B][N] ///
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7, inf = 0x3f3f3f3f;
const char sp = ' ', nl = '\n';
ifstream fin("cerere.in");
ofstream fout("cerere.out");

const int nmax = 1e5;
int n, v[nmax + 1], dp[nmax + 1];
vector<int> g[nmax + 1], path;

void dfs(int node) {
    if (v[node]) {
        dp[node] = dp[path[path.size() - v[node]]] + 1;
    }
    path.push_back(node);
    for (auto& son : g[node]) {
        dfs(son);
    }
    path.pop_back();
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    fin >> n;
    vector<int> root(n + 1, 1);
    for (int i = 1; i <= n; ++i) {
        fin >> v[i];
    }
    for (int i = 1; i < n; ++i) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        root[y] = 0;
    }
    int rt = 0;
    for (int i = 1; i <= n; ++i) {
        if (root[i]) {
            rt = i;
        }
    }
    dfs(rt);
    for (int i = 1; i <= n; ++i) {
        fout << dp[i] << sp;
    }
}