Source Code
#define F first
#define S second
#define rep(i,a,b) for(int i=a;!(a==b&&i!=b)&&((i<=b&&b>=a)||(i>=b&&a>=b));i+=(a<=b?1:-1))
#define pb push_back
#define Fbitl __builtin_ffs
#define bit1 __builtin_popcount
#include <iostream>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <map>
#include <unordered_map>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<string, string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vl> vvl;
bool visa[(int)1e6] ;
vi x[200005] ;
int v[200005];
pii mn[200005];
int dfs ( int a , queue<int> z ) {
	z.push(a);
	int b = z.front();
	z.pop();
	if ( b != 0 ) {
		if ( mn[b].F > abs(v[b]-v[a]) ) {
			mn[b] = {min(mn[b].F,abs(v[b]-v[a])),a};
		}
		
	}
	for ( auto i : x[a] ) {
		dfs(i,z);
	}
	return 0;
}
int main(){
   ios_base::sync_with_stdio(0);cin.tie(0);
    int n,p ;
    cin >> n;
    for ( int i = 2 ; i <= n ; i++ ) { 
    	cin >> p;
    	x[p].pb(i);
    }
    for ( int i = 1 ; i <= n ; i++ ) {
    	cin >> v[i] ;
    	mn[i].F = int(1e9) + 5 ;
    }
    queue <int> z ;
    for(int i=0;i<4;i++)z.push(0);
    dfs(1,z);
    for ( int i = 1 ; i <= n ; i++ )  {
    	cout << (mn[i].F==int(1e9) + 5?0:mn[i].S) << " " ;
    }
   return 0;
}
Copy
Find a Friend SAAD
GNU G++17
173 ms
137.5 MB
Accepted