Cod sursa(job #2948858)

Utilizator CiuiGinjoveanu Dragos Ciui Data 28 noiembrie 2022 17:32:42
Problema Cerere Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.03 kb
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <algorithm>
#include <utility>
#include <cmath>
#include <map>
#include <deque>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <limits.h>
using namespace std;

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

const int MAX_SIZE = 100000;

vector<int> tree[MAX_SIZE + 1], reverseTree[MAX_SIZE + 1];
int ancestorDegree[MAX_SIZE + 1], noHands[MAX_SIZE + 1];
int noMonkeys;

void reverse(int current) {
    if (ancestorDegree[current] == 0) {
        noHands[current] = 0;
        return;
    }
    queue<int> positions;
    positions.push(current);
    int noAncestors = ancestorDegree[current];
    int curDegree = 0;
    int ancestor = -1;
    while (!positions.empty()) { // ne deplasam pana cand ajungem la nivelul dictat de datele de intrare.
        int cur = positions.front();
        positions.pop();
        if (curDegree == noAncestors) {
            ancestor = cur;
        }
        for (int next : reverseTree[cur]) {
            positions.push(next);
        }
        ++curDegree;
    }
    noHands[current] = noHands[ancestor] + 1;
}

void findNoHands(int root) {
    queue<int> positions;
    positions.push(root);
    while (!positions.empty()) {
        int cur = positions.front();
        reverse(cur);
        positions.pop();
        for (int next : tree[cur]) {
            positions.push(next);
        }
    }
    for (int i = 1; i <= noMonkeys; ++i) {
        fout << noHands[i] << " ";
    }
}

int main() {
    fin >> noMonkeys;
    for (int i = 1; i <= noMonkeys; ++i) {
        fin >> ancestorDegree[i];
        noHands[i] = -1;
    }
    for (int i = 1; i < noMonkeys; ++i) {
        int parent, child;
        fin >> parent >> child;
        tree[parent].push_back(child);
        reverseTree[child].push_back(parent);
    }
    int root = -1;
    for (int i = 1; i <= noMonkeys; ++i) {
        if (reverseTree[i].size() == 0) {
            root = i;
            break;
        }
    }
    findNoHands(root);
}