Cod sursa(job #2922412)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 8 septembrie 2022 10:54:39
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <fstream>
#include <vector>

using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};
InParser fin("cerere.in");
ofstream fout("cerere.out");

const int maxN = 100005;

int n, s[maxN], ans[maxN], lvl[maxN];
bool used[maxN];
vector <int> G[maxN];

void dfs(int nod, int depth)
{
    lvl[depth] = nod;
    if(s[nod] == 0)
        ans[nod] = 0;
    else
        ans[nod] = ans[lvl[depth - s[nod]]] + 1;
    for(int vecin : G[nod])
        dfs(vecin, depth + 1);
}

int main()
{
    fin >> n;
    for(int i = 1; i <= n; i++)
        fin >> s[i];
    for(int i = 1; i < n; i++)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        used[y] = 1;
    }
    int root = -1;
    for(int i = 1; i <= n && root == -1; i++)
        if(!used[i])
            root = i;
    dfs(root, 0);
    for(int i = 1; i <= n; i++)
        fout << ans[i] << ' ';
    return 0;
}