Cod sursa(job #973633)

Utilizator toranagahVlad Badelita toranagah Data 14 iulie 2013 22:08:51
Problema Cerere Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.9 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

ifstream fin("cerere.in");
ofstream fout("cerere.out");

const int MAX_N = 100100;

int N;
vector<int> graph[MAX_N];
int root;
int father[MAX_N];
int query[MAX_N];
int answer[MAX_N];
int st[2 * MAX_N];
int st_top = 0;

void dfs(int node);

int main() {
  fin >> N;
  for (int i = 1; i <= N; ++i) {
    fin >> query[i];
  }

  for (int i = 1, a, b; i < N; ++i) {
    fin >> a >> b;
    graph[a].push_back(b);
    father[b] = a;
  }

  root = 1;
  while (father[root] != 0) {
    root = father[root];
  }

  dfs(root);

  for (int i = 1; i <= N; ++i) {
    fout << answer[i] << ' ';
  }
}

void dfs(int node) {
  st[++st_top] = node;
  
  if (query[node] == 0) {
    answer[node] = 0;
  } else {
    answer[node] = answer[st[st_top - query[node]]] + 1;
  }

  for (auto son : graph[node]) {
    dfs(son);
  }

  --st_top;
}