Cod sursa(job #2553771)

Utilizator memecoinMeme Coin memecoin Data 22 februarie 2020 11:49:27
Problema Cerere Scor 65
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.5 kb
#include <fstream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string.h>
#include <queue>
#include <stack>

#define INF 0x3f3f3f3f

using namespace std;

#ifdef DEBUG
string name = "data";
#else
string name = "cerere";
#endif

ifstream fin(name + ".in");
ofstream fout(name + ".out");

#define MAXN 100005

int n;

int c[MAXN];
vector<int> g[MAXN];
vector<int> gt[MAXN];

int parent[MAXN];

int st[MAXN];
int cnt[MAXN];

void dfs(int node, int lvl) {
    if (c[node] == 0) {
        parent[node] = 0;
    } else {
        parent[node] = st[lvl - c[node]];
    }
    
    for (auto y: g[node]) {
        st[lvl] = node;
        dfs(y, lvl + 1);
    }
}

int count(int node) {
    if (cnt[node] != INF) {
        return cnt[node];
    }
    
    if (parent[node] == 0) {
        return 0;
    }
    
    int rez = 1 + count(parent[node]);
    
    cnt[node] = rez;
    
    return rez;
}

int main() {
    
    fin >> n;
    
    memset(cnt, 0x3f, sizeof(cnt));
    
    for (int i = 1; i <= n; ++i) {
        fin >> c[i];
    }
    
    for (int i = 1; i <= n; ++i) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    
    int boss = 0;
    
    for (int i = 1; i <= n; ++i) {
        if (gt[i].size() == 0) {
            boss = i;
        }
    }
    
    dfs(boss, 0);
    
    for (int i = 1 ; i<= n; ++i) {
        fout << count(i) << " ";
    }
    
    return 0;
}