Pagini recente » Cod sursa (job #161694) | Cod sursa (job #2756724) | Cod sursa (job #2263800) | Cod sursa (job #1628976) | Cod sursa (job #2957068)
#include<fstream>
#include<vector>
#define NMAX 100 000
#define LOG 18
std::ifstream cin("cerere.in");
std::ofstream cout("cerere.out");
using namespace std;
int n, u, v, root;
vector<int>g[NMAX + 1], ancestor, viz;
int up[NMAX + 1][LOG];
void dfs(int node = root, int parent = 0) {
for (auto i : g[node]) {
if (i ^ parent) {
up[i][0] = node;
for (int j = 1; j < LOG; ++j)
up[i][j] = up[up[i][j - 1]][j - 1];
dfs(i, node);
}
}
}
int binary_lifting(int node, int k) {
for (int i = LOG - 1; i >= 0; --i)
if (k & (1 << i)) node = up[node][i];
return node;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
ancestor = viz = vector<int>(n + 1);
for (int i = 1; i <= n; i++) cin >> ancestor[i];
for (int i = 1; i < n; ++i) {
cin >> u >> v;
g[u].push_back(v);
viz[v] = 1;
}
for (int i = 1; i <= n; i++)
if (!viz[i]) root = i;
dfs();
for (int i = 1; i <= n; i++) {
int ki = ancestor[i];
int new_ancestor = i;
int cnt = 0;
while (ki) {
cnt++;
new_ancestor = binary_lifting(new_ancestor, ki);
ki = ancestor[new_ancestor];
}
cout << cnt << " ";
}
return 0;
}