Pagini recente » Cod sursa (job #2481486) | Cod sursa (job #1375927) | Cod sursa (job #2006681) | Cod sursa (job #2689660) | Cod sursa (job #2130787)
#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();
}