Pagini recente » Cod sursa (job #1896167) | Cod sursa (job #2620950) | Cod sursa (job #1425111) | Cod sursa (job #2972228) | Cod sursa (job #1450702)
#include <fstream>
#include <vector>
#define NMax 100010
using namespace std;
ifstream f("cerere.in");
ofstream g("cerere.out");
int nodes, edges, st[NMax], top, ancestor[NMax], extgr[NMax], depth[NMax];
bool mark[NMax];
vector<int> G[NMax];
void DFS(int node)
{
mark[node] = 1;
st[++top] = node;
if (ancestor[node] != 0)
depth[node] = depth[st[top - ancestor[node]]] + 1;
else
depth[node] = 0;
for (vector<int>::iterator it = G[node].begin(); it != G[node].end(); ++it)
if (!mark[*it])
DFS(*it);
--top;
}
int main()
{
f >> nodes;
for (int i = 1; i <= nodes; ++i)
f >> ancestor[i];
int n1, n2;
for (int i = 1; i <= nodes - 1; ++i) {
f >> n1 >> n2;
G[n1].push_back(n2);
extgr[n2]++;
}
int rad = 0;
for (int i = 1; i <= nodes; ++i) {
if (extgr[i] == 0) {
rad = i;
break;
}
}
DFS(rad);
for (int i = 1; i <= nodes; i++)
g << depth[i] << " ";
}