Cod sursa(job #2130787)

Utilizator DawlauAndrei Blahovici Dawlau Data 13 februarie 2018 21:46:47
Problema Cerere Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.21 kb
#include<fstream>
#include<list>
using namespace std;
ifstream fin("cerere.in");
ofstream fout("cerere.out");
const int NMAX = 1e5 + 5;

list<int> graph[NMAX];

int Stack[NMAX], father[NMAX], kthAncestor[NMAX], stepsCount[NMAX];
int nodesCount;

inline void read_data(){

    fin >> nodesCount;

    int node;
    for(node = 1; node <= nodesCount; ++node){

        fin >> kthAncestor[node];
        father[node] = node;
    }

    int edge, from, to;
    for(edge = 1; edge <= nodesCount - 1; ++edge){

        fin >> from >> to;
        graph[from].push_back(to);
        father[to] = from;
    }
}

inline int getRoot(){

    int root;
    for(root = 1; root != father[root]; root = father[root]);
    return root;
}

void DFS(int node, int StackSize){

    Stack[StackSize] = node;

    if(kthAncestor[node])
        stepsCount[node] = 1 + stepsCount[Stack[StackSize - kthAncestor[node]]];

    for(const auto &nextNode: graph[node])
        DFS(nextNode, StackSize + 1);
}

inline void print(){

    int node;
    for(node = 1; node <= nodesCount; ++node)
        fout << stepsCount[node] << ' ';
}

int main(){

    read_data();
    DFS(getRoot(), 1);
    print();
}