Cod sursa(job #1991874)

Utilizator DjokValeriu Motroi Djok Data 18 iunie 2017 16:10:27
Problema Cerere Scor 30
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 0.87 kb
#include <bits/stdc++.h>
using namespace std;

const int N = 100005;

int i, j, n, x, y, k[N], dpa[20][N], root, rs[N];
vector<int> lda[N];

void dfs(int x) {
  int now = x;
  if(!k[now]) rs[x] = 0;
  else {
    for(int i = 30; i >= 0; --i)
      if(k[x] & (1 << i)) now = dpa[i][now];
    rs[x] = rs[now] + 1;
  }

  for(auto to : lda[x]) dfs(to);
}

int main() {
  ifstream cin("cerere.in");
  ofstream cout("cerere.out");
  ios_base::sync_with_stdio(0);

  cin >> n;
  for(i = 1; i <= n; ++i) cin >> k[i];
  for(i = 1; i < n; ++i) {
    cin >> x >> y;
    lda[x].push_back(y);
    dpa[0][y] = x;
  }

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

  for(i = 1; i < 20; ++i)
    for(j = 1; j <= n; ++j)
      dpa[i][j] = dpa[i - 1][dpa[i - 1][j]];

  dfs(root);

  for(i = 1; i <= n; ++i) cout << rs[i] << " \n"[i == n];

  return 0;
}