Cod sursa(job #2669924)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 8 noiembrie 2020 14:22:49
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

const int NMAX = 1e5;

int n;

std::vector<int> graf[1 + NMAX];
std::vector<std::pair<int, int>> st;

int dp[1 + NMAX];
int k[1 + NMAX];
bool isnt_root[1 + NMAX];

void read() {
  std::ifstream in("cerere.in");

  in >> n;

  for (int i = 1; i <= n; ++i)
    in >> k[i];

  int x, y;
  while (in >> x >> y) {
    graf[x].push_back(y);
    isnt_root[y] = true;
  }

  in.close();
}

void dfs() {
  int root = -1;

  for (int i = 1; i <= n; ++i) {
    if (!isnt_root[i]) {
      root = i;
      break;
    }
  }

  st.emplace_back(root, 0);
  dp[root] = 0;

  while (!st.empty()) {
    int nod = st.back().first;
    int ind = st.back().second;

    if (st.back().second == 0) {
      if (k[nod] == 0)
        dp[nod] = 0;
      else
        dp[nod] = 1 + dp[st[st.size() - k[nod] - 1].first];
    }

    if (ind < graf[nod].size()) {
      st.back().second++;

      st.emplace_back(graf[nod][ind], 0);
    } else {
      st.pop_back();
    }

  }
}

int main() {
  read();

  dfs();

  std::ofstream out("cerere.out");
  for (int i = 1; i <= n; ++i)
    out << dp[i] << ' ';

  out.close();
  return 0;
}