Source Code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define f first
#define s second
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()

const int inf = 2e9;
const ll infll = 1e18;
const int M = 1000000007;
const int N = 2e5;

int n, p[N+1];
vector<int> g[N+1], ans;

void dfs(int srce, int u, int d){
    if(d == 4){
        if(ans[srce] == 0){
            ans[srce] = u;
            return;
        }
        if(abs(p[srce] - p[u]) < abs(p[srce] - p[ans[srce]])){
            ans[srce] = u;
        }
        else if (abs(p[srce] - p[u]) == abs(p[srce] - p[ans[srce]])){
            ans[srce] = min(ans[srce], u);
        }
        return;
    }
    for(auto v : g[u]){
        dfs(srce, v, d+1);
    }
}

int main(){
    scanf("%d", &n);
    for(int i = 2, x; i <= n; ++i){
        scanf("%d", &x);
        g[x].pb(i);
    }
    for(int i = 1; i <= n; ++i) scanf("%d", &p[i]);
    ans.assign(n+1, 0);

    for(int i = 1; i <= n; ++i){
        dfs(i, i, 0);
        printf("%d ", (ans[i] == inf+1 ? 0 : ans[i]));
    }

    puts("");

}
Copy
Find a Friend Hambubger
GNU G++17
164 ms
14.1 MB
Accepted