Source Code
#pragma GCC optimize ("O3")
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define printv(x) for(int i : x) cout << i << " "; cout << endl;

#define fl(x) for(int i = 0 ; i < x.size(); i++ )
#define yes cout << "YES" << endl;
#define no cout << "NO" << endl

const int N= 2e5 + 5 ;


vector<int> g[N];

int p[N];

vector<int> pos ;

void dfs(int node ,int level) {

    if(level == 4 ) {
        pos.push_back(node);
        return ;
    }
    for(int x : g[node]) {
        dfs(x , level + 1);
    }
}

void solve() {
    int n ;
    cin >> n ;

    for (int i = 2; i <= n; ++i) {
        int x;
        cin >> x;

        g[x].push_back(i);
    }

    for (int i = 1; i <= n ; ++i) {
        int x;
        cin  >>x ;
        p[i]= x ;
    }



    for(int i =1 ; i <= n ; i++ ) {
        dfs(i , 0 );
        int min = INT_MAX ;
        int index = -1 ;

        for(int x : pos) {
            if(abs(p[x] - p[i]) < min ) {
                min = abs(p[x] - p[i]);
                index = x ;
            }
            else if (abs(p[x] - p[i]) == min) {
                if(x < index ){
                    index = x;
                }
            }
        }
        if(index == -1)
            index = 0 ;
        cout << index << " ";
        pos.clear();
    }

    cout << endl;
}

int32_t main() {
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

//    int t ; cin >> t; while(t--) solve();
    solve();

//    cout << INT_MAX << endl << INT_MIN ;
    return 0;

}
Copy
Find a Friend Shweiki
GNU G++17
133 ms
14.0 MB
Accepted