Pagini recente » Cod sursa (job #520232) | Cod sursa (job #381021) | Cod sursa (job #2988843) | Cod sursa (job #1055157) | Cod sursa (job #1991716)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream in("cerere.in");
ofstream out("cerere.out");
const int maxn = 100005;
vector <int> down[maxn];
vector <int> v;
int sol[maxn];
int str[maxn];
int K[maxn];
int F[maxn];
int rad = 0;
void dfs(int nod)
{
if(K[nod] == 0 || sol[nod] != 0)
return;
dfs(str[nod]);
sol[nod] = sol[str[nod]] + 1;
}
void calcstr(int nod)
{
if(nod == rad)
{
v.push_back(nod);
for(auto it : down[nod])
calcstr(it);
return;
}
str[nod] = v[v.size() - K[nod]];
v.push_back(nod);
for(auto it : down[nod])
calcstr(it);
v.pop_back();
}
int main()
{
int n;
in >> n;
for(int i = 1; i <= n; i++)
in >> K[i];
for(int i = 1; i <= n; i++)
{
int x, y;
in >> x >> y;
F[y] = x;
down[x].push_back(y);
}
int nod = 1;
while(F[nod] != 0)
nod = F[nod];
rad = nod;
calcstr(rad);
for(int i = 1; i <= n; i++)
if(!sol[i])
dfs(i);
for(int i = 1; i <= n; i++)
out << sol[i] << " ";
out << "\n";
return 0;
}