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

using namespace std;

vector<vector<int>>v;
vector<vector<int>>s;
int p[200003];
int vis[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) {
			s[a].push_back(y);
		}
		q.pop();
	}
}

void solve() {
	int n;
	cin >> n;
	s.resize(n + 2);
	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++) {
		int ans = n + 1;
		if (s[i].size()) {
			int t = 2000000000;
			for (int j = 0; j < s[i].size(); j++) {
				if (t > abs(p[i] - p[s[i][j]])) {
					ans = s[i][j];
					t = abs(p[i] - p[s[i][j]]);
				}
				else if (t == abs(p[i] - p[s[i][j]])) {
					if (ans > s[i][j]) {
						ans = s[i][j];
					}
				}
			}
		}
		if (ans == n + 1) {
			ans = 0;
		}
		cout << ans << " ";
	}
}
int main() {
	int t = 1;
	//cin >> t;
	while (t--) {
		solve();
	}
}
Copy
Find a Friend lafi-Odeh
GNU G++17
186 ms
24.0 MB
Accepted