Cod sursa(job #3177978)

Utilizator bombatongaMunteanu David Ioan bombatonga Data 30 noiembrie 2023 18:53:45
Problema Cerere Scor 100
Compilator cpp-32 Status done
Runda Arhiva de probleme Marime 0.96 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <iostream>

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

const int nMax = 1e5 + 5;

std::bitset<nMax> not_root, used;

std::vector<int> path, graph[nMax];

int ancestor[nMax], ans[nMax];

void dfs(int node, int height) {
	used[node] = 1;
	path.push_back(node);
	ans[node] = 1 + ans[path[height - ancestor[node]]];
	for (int i : graph[node])
		if (!used[i])
			dfs(i, height + 1);
	path.resize(path.size() - 1);
}

int main() {
	int N;
	fin >> N;
	for (int i = 1; i <= N; i++)
		fin >> ancestor[i], ans[i] = -1;

	for (int i = 1; i < N; i++) {
		int x, y;
		fin >> x >> y;
		not_root[y] = 1;
		graph[x].push_back(y);
		graph[y].push_back(x);

	}
	for (int i = 1; i <= N; i++)
		if (!not_root[i])
		{
			std::cout << "OK";
			dfs(i, 0);
			break;
		}

	for (int i = 1; i <= N; i++)
		fout << ans[i] << ' ';

	fin.clear(); fout.clear();
	return 0;
}