Source Code
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
 
#define pb push_back
#define mk make_pair
#define ff first
#define ss second
#define fast ios::sync_with_stdio(false);cin.tie(0);
 
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef tree<int, null_type, less<int>,
        rb_tree_tag, tree_order_statistics_node_update> ordered_set;

vector<int> v[200005];
int a[200005];

int calc(int r, int len, int R){
	int ret = 1e9;
	if(len > 4) return ret;
	if(len == 4) return r;
	int mn = 1e9;
	for(int i: v[r]){
		int temp = calc(i, len+1,R);
		if(temp == 1e9) continue;
		if(abs(a[R] - a[temp]) < mn){
			
			ret = temp;
			mn = abs(a[R] - a[temp]);
			}
		else if(abs(a[R] - a[temp]) < mn && temp < ret)
			ret = temp;
		}
	return ret;
	}

int main(){
	fast
	
	int n;
	cin>>n;
	int p[n+1];
	for(int i=2;i<=n;i++) {
		cin>>p[i];
		v[p[i]].pb(i);
			
		}
	
	for(int i=1;i<=n;i++) cin>>a[i];
	
	for(int i=1;i<=n;i++){
		int ans = calc(i,0,i);
		if(ans == 1e9) cout<<0<<' ';
		else cout<<ans<<' ';
		}
	
return 0;
}
Copy
Find a Friend Bahaa
GNU G++17
153 ms
14.0 MB
Accepted