Cod sursa(job #2673068)

Utilizator IRadu1529Radu Ionescu IRadu1529 Data 15 noiembrie 2020 18:31:15
Problema Cerere Scor 0
Compilator cpp-32 Status done
Runda ursus_retro_fara_alcool Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("cerere.in");
ofstream fout("cerere.out");
const int N = 100001;
int n, logN, cond, rez, ans[N], send[N], d[17][N], nod;///logN = max 17
void solve(int el);
int main() {
	fin >> n;
	logN = log2(n);
	for (int i = 1; i <= n; ++i) {
		ans[i] = -1;
		fin >> send[i];
		if (!send[i]) {
			ans[i] = 0;
			d[0][i] = 0;
		}
	}
	int a, b;
	for (int i = 1; i < n; ++i) {
		fin >> a >> b;
		d[0][b] = a;
	}

	for (int pw = 1; pw <= logN; ++pw)
		for (int i = 1; i <= n; ++i)
			d[pw][i] = d[pw - 1][d[pw - 1][i]];

	for (int i = 1; i <= n; ++i) {
		if (ans[i] == 0) {
			ans[i] = 0;
			fout << "0 ";
			continue;
		}
		cond = rez = 0;
		nod = i;
		solve(i);
		ans[i] = rez;
		fout << rez << " ";
	}
}

void solve(int el) {
	while (ans[el]) {
		for (int pw = logN; pw >= 0; --pw)
			if (((1 << pw) & send[el])) {
				if (d[pw][nod] < el) {
					el = ans[d[pw][nod]];
					rez += ans[d[pw][nod]];
					cond = 1;
					break;
				}
				nod = d[pw][nod];
			}

		++rez;
		if (!cond)
			el = nod;
	}
}