Source Code
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

vector<vector<int>>v;
int p[200003];
int vis[200003];
int ans[200003];
void bfs(int n) {
	queue<int>q;
	q.push(1);
	while (!q.empty()) {
		int y = q.front();
		for (int i = 0; i < v[y].size(); i++) {
			int x = v[y][i];
			if (!vis[x]) {
				vis[x] = y;
				q.push(x);
			}
		}
		int a = 0, b = 0, c = 0, d = 0;
		d = vis[y];
		c = vis[d];
		b = vis[c];
		a = vis[b];
		if (a && b && c && d) {
			if (!ans[a]) {
				ans[a] = y;
			}
			else {
				int x = abs(p[a] - p[ans[a]]), z = abs(p[a] - p[y]);
				if (x > z) {
					ans[a] = y;
				}
				else if (x == z) {
					if (ans[a] > y) {
						ans[a] = y;
					}
				}
			}
		}
		q.pop();
	}
}

void solve() {
	int n;
	cin >> n;
	v.resize(n + 2);
	int a;
	for (int i = 2; i <= n; i++) {
		cin >> a;
		v[a].push_back(i);
	}
	for (int i = 1; i <= n; i++) {
		cin >> a;
		p[i] = a;
	}
	bfs(n);
	for (int i = 1; i <= n; i++) {
		cout << ans[i] << " ";
	}
}
int main() {
	int t = 1;
	//cin >> t;
	while (t--) {
		solve();
	}
}
Copy
Find a Friend lafi-Odeh
GNU G++17
171 ms
14.7 MB
Accepted