Cod sursa(job #1470104)

Utilizator blasterzMircea Dima blasterz Data 10 august 2015 13:36:47
Problema Cerere Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.32 kb
#include <cstdio>
#include <vector>

using namespace std;

#define N 100001

#define dim 8192
char ax[dim];
int ps;

void cit(int &x) {
	while (ax[pz] < '0' || ax[pz] > '9')
		if (++pz == dim)
			fread(ax, 1, dim, stdin), pz = 0;
	while (ax[pz] >= '0' && ax[pz] <= '9') {
		x = x * 10 + ax[pz] - '0';
		if (++pz == dim)
			fread(ax, 1, dim, stdin), pz = 0;
	}
}

vector<int> a[N];

int parent[N];

int st[N];
int n;

int g[N];
int root = 0;
bool used[N];
int nst;

int sol[N];

void dfs(int u) {
    used[u] = true;
    st[++nst] = u;

    if (nst - parent[u] >= 1 && parent[u] != 0)
        sol[u] = sol[ st[ nst - parent[u] ] ] + 1;

    for (vector<int>::iterator it = a[u].begin(); it != a[u].end(); ++it)
        if (!used[*it]) {
            dfs(*it);
        }

    --nst;
}


int main() {

    freopen ("cerere.in", "r", stdin);
    freopen ("cerere.out", "w", stdout);
    cit(n);
    int i;
    for (i = 1; i <= n; ++i)
       	cit(parent[i]);

    int p, q;

    for (i = 1; i < n; ++i) {
        cit(p); cit(q);
        a[p].push_back(q);
        //a[q].push_back(p);
        g[q]++;
    }

    for (i =1 ;i <= n; ++i)
        if (!g[i])
            root = i;

    dfs(root);

    for (i = 1; i <= n; ++i)
        printf ("%d ", sol[i]);
    printf ("\n");
}