Cod sursa(job #2635607)

Utilizator stefan.popescuPopescu Stefan stefan.popescu Data 14 iulie 2020 23:50:04
Problema Cerere Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
using namespace std;
ifstream in ("cerere.in");
ofstream out("cerere.out");
int n, x, y;
vector <vector <int> > muchii;
vector <bool> isRoot;
vector <int> ancestorNeeded, neededSteps;
deque <int> actStk;
void dfs(int nod)
{
    actStk.push_front(nod);

    if(ancestorNeeded[nod]==0) neededSteps[nod] = 0;
    else
        neededSteps[nod] = neededSteps [ actStk [ ancestorNeeded [ nod ] ] ] + 1;

    for(auto & x : muchii[nod])
        dfs(x);

    actStk.pop_front();
}
int main()
{
    in>>n;
    muchii.resize(n+1); isRoot.resize(n+1, true); neededSteps.resize(n+1); ancestorNeeded.resize(n+1);
    for(int i=1; i<=n; i++)
        in>>ancestorNeeded[i];
    for(int i=1; i<=n-1; i++)
        in>>x>>y, isRoot[y]=false, muchii[x].push_back(y);

    for(int i=1; i<=n; i++)
        if(isRoot[i])
            dfs(i);
    for(int i=1; i<=n; i++)
        out<<neededSteps[i]<<" ";
    return 0;
}