Cod sursa(job #3362162)

Utilizator filipdanieloanFilip-Daniel Oancea filipdanieloan Data 3 august 2026 21:15:44
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;

vector<int> stramos, dist;
vector<vector<int>> adj;
vector<int> stk;

void dfs(int node) {
	stk.push_back(node);
	if (stramos[node] != 0) {
		dist[node] = dist[stk[stk.size() - 1 - stramos[node]]] + 1;
	}
	for (auto& i : adj[node]) {
		dfs(i);
	}
	stk.pop_back();
}

signed main() {
	#ifndef LOCAL
	cin.tie(nullptr)->sync_with_stdio(false);
	freopen("cerere.in", "r", stdin);
	freopen("cerere.out", "w", stdout);
	#endif
	
	int n; cin >> n;
	stramos.resize(n + 1), dist.resize(n + 1);
	for (int i = 1; i <= n; ++i) 
		cin >> stramos[i];
	
	adj.resize(n + 1);
	vector<bool> fathered(n + 1);
	for (int i = 1; i < n; ++i) {
		int x, y; cin >> x >> y;
		adj[x].push_back(y);
		fathered[y] = true;
	}
	
	int absolute;
	for (int i = 1; i <= n; ++i) {
		if (!fathered[i]) {
			absolute = i;
			break;
		}
	}
	
	dfs(absolute);
	
	for (int i = 1; i <= n; ++i) {
		cout << dist[i] << ' ';
	}
	cout << '\n';
	
	return 0;
}