Cod sursa(job #2599664)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 11 aprilie 2020 17:49:21
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.96 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

int cer[MAXN], ans[MAXN];
bool fiu[MAXN];
vector<int> graf[MAXN], lant;

void dfs(int nod){
    lant.push_back(nod);
    if((int)graf[nod].size() == 0) return;
    for(auto x: graf[nod]){
        if(cer[x] > 0){
            int stramos = lant[lant.size() - cer[x]];
            ans[x] = ans[stramos] + 1;
        }
        dfs(x);
        lant.pop_back();
    }
}

int main()
{
    ifstream fin("cerere.in");
    ofstream fout("cerere.out");
    int n;
    fin >> n;
    for(int i = 1; i <= n; ++i)
        fin >> cer[i];
    for(int i = 1; i < n; ++i){
        int x, y;
        fin >> x >> y;
        graf[x].push_back(y);
        fiu[y] = 1;
    }
    int root = 0;
    for(int i = 1; i <= n; ++i){
        if(!fiu[i]){
            root = i;
            break;
        }
    }
    dfs(root);
    for(int i = 1; i <= n; ++i) fout << ans[i] << " ";
    return 0;
}