Pagini recente » Cod sursa (job #1966850) | Cod sursa (job #2339504) | Cod sursa (job #2251813) | Cod sursa (job #2239392) | Cod sursa (job #2454509)
#include <cstdio>
using namespace std;
const int N = 100000 + 7;
const int K = 17;
int n, jump[N];
int anc[K][N];
int p[N];
int dp[N];
int calc(int i) {
if (dp[i] == -1) {
dp[i] = 1 + calc(p[i]);
}
return dp[i];
}
int cn[N], k, top, top2;
int main() {
freopen ("cerere.in", "r", stdin);
freopen ("cerere.out", "w", stdout);
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &jump[i]);
}
for (int i = 1; i < n; i++) {
int a, b;
scanf("%d %d", &a, &b);
anc[0][b] = a;
}
for (int i = 1; i <= n; i++) {
if (anc[0][i] > 0) {
cn[++top] = i;
}
}
while (top) {
k++;
top2 = 0;
for (int j = 1; j <= top; j++) {
anc[k][cn[j]] = anc[k - 1][anc[k - 1][cn[j]]];
if (anc[k][cn[j]] > 0) {
cn[++top2] = cn[j];
}
}
top = top2;
}
for (int i = 1; i <= n; i++) {
dp[i] = -1;
if (jump[i] == 0) {
dp[i] = 0;
}
p[i] = i;
for (int bit = 0; (1 << bit) <= jump[i]; bit++) {
if (jump[i] & (1 << bit)) {
p[i] = anc[bit][p[i]];
}
}
}
for (int i = 1; i <= n; i++) {
printf("%d ", calc(i));
}
printf("\n");
return 0;
}