Pagini recente » Cod sursa (job #2796117) | Cod sursa (job #1630801) | Cod sursa (job #409960) | Cod sursa (job #1852656) | Cod sursa (job #2136169)
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
#define nmax 100005
using namespace std;
FILE *f=fopen("cerere.in","r");
FILE *g=fopen("cerere.out","w");
vector<int>Q[nmax],topsorted,tobesorted,ancestors;
int n,stramos[nmax],tata[nmax],intel[nmax],prev;
void read()
{
fscanf(f,"%d",&n);
for (int i=1; i<=n; ++i)
fscanf(f,"%d",&stramos[i]);
for (int i=1; i<n; ++i)
{
int a,b;
fscanf(f,"%d %d",&a,&b);
Q[a].push_back(b);
tata[b]=a;
}
}
void topsort(int nod)
{
for (auto w:Q[nod])
topsort(w);
topsorted.push_back(nod);
}
void solve()
{
for (int i=1; i<=n; ++i)
if (!tata[i])
{
tata[i]=i;
tobesorted.push_back(i);
}
for (auto w:tobesorted)
topsort(w);
reverse(topsorted.begin(),topsorted.end());
for (auto w:topsorted)
{
while (ancestors.size()&&ancestors.back()!=tata[w])
{
ancestors.pop_back();
}
if (!stramos[w])
{
ancestors.push_back(w);
continue;
}
else
{
intel[w]=1+intel[ancestors[ancestors.size()-stramos[w]]];
ancestors.push_back(w);
}
}
for (int i=1; i<=n; ++i)
fprintf(g,"%d ",intel[i]);
}
int main()
{
read();
solve();
return 0;
}