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++) {
			if (!vis[v[y][i]]) {
				vis[v[y][i]] = y;
				q.push(v[y][i]);
			}
		}
		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 {
				if (abs(p[a]-p[ans[a]]) > abs(p[a]-p[y])) {
					ans[a] = y;
				}
				else if (abs(p[a] - p[ans[a]]) == abs(p[a] - p[y])) {
					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
221 ms
14.8 MB
Accepted