Cod sursa(job #2016383)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 29 august 2017 11:48:08
Problema Cerere Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.53 kb
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <climits>
#include <queue>
using namespace std;
typedef long long LL;

#ifdef INFOARENA
#define ProblemName "cerere"
#endif

#define MCONCAT(A, B) A B
#ifdef ProblemName
#define InFile MCONCAT(ProblemName, ".in")
#define OuFile MCONCAT(ProblemName, ".out")
#else
#define InFile "fis.in"
#define OuFile "fis.out"
#endif

const int MAXN = 100010, MAXLOG = 20;
int ans[MAXN], p[MAXN][MAXLOG], K[MAXN];
int N;

void pre() {
  for (int i = 1; i < MAXLOG; ++i)
  for (int j = 0; j < N; ++j) {
    if (p[j][i - 1] < 0)
      continue;
    p[j][i] = p[p[j][i - 1]][i - 1];
  }
}

int kthAncestor(int x, int k, int curlog) {
  if (k == 0 || curlog < 0)
    return x;
  if (((1 << curlog) > k) || (p[x][curlog] < 0))
    return kthAncestor(x, k, curlog - 1);
  return kthAncestor(p[x][curlog], k - (1 << curlog), curlog - 1);
}

int solve(int x) {
  if (ans[x] >= 0)
    return ans[x];
  if (K[x] == 0)
    return (ans[x] = 0);
  int kth = kthAncestor(x, K[x], MAXLOG - 1);
  return (ans[x] = solve(kth) + 1);
}

int main() {
  assert(freopen(InFile, "r", stdin));
  assert(freopen(OuFile, "w", stdout));
  memset(ans, 0xFF, sizeof(ans));
  memset(p, 0xFF, sizeof(p));
  scanf("%d", &N);
  for (int i = 0; i < N; ++i)
    scanf("%d", &K[i]);
  for (int i = 0; i < N - 1; ++i) {
    int a, b;
    scanf("%d%d", &a, &b);
    --a, --b;
    p[b][0] = a;
  }
  pre();
  for (int i = 0; i < N; ++i)
    printf("%d ", solve(i));
  putchar('\n');
  return 0;
}