Source Code
#include<bits/stdc++.h>
using namespace std;

const int N = 2e5 + 5;
int n;
int parent[N], pers[N], ans[N], _4thParent[N];


void solve(){
    cin>>n;
    for(int i = 2 ; i<=n ; i++){
        cin>>parent[i];
        int loc = i, cnt = 0;
        while(loc != 1 && cnt<4){
            cnt++;
            loc = parent[loc];
        }
        if(cnt == 4)
            _4thParent[i] = loc;
    }
    for(int i = 1 ; i<=n ; i++)
        cin>>pers[i];
    for(int i = 1 ; i<=n ; i++){
        if(_4thParent[i] == 0)
            continue;
        if(ans[_4thParent[i]] == 0){
            ans[_4thParent[i]] = i;
            continue;
        }
        int cur = abs(pers[i] - pers[_4thParent[i]]);
        int prev = abs(pers[ans[_4thParent[i]]] - pers[_4thParent[i]]);
        if(cur < prev)
            ans[_4thParent[i]] = i;
    }
    for(int i = 1 ; i<=n ; i++){
        cout<<ans[i]<<" ";
    }
}
 
int main(){
    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    #ifndef ONLINE_JUDGE
        freopen("input.in","r",stdin);
    #endif


    int tt = 1;
    // cin>>tt;
    while(tt--)
        solve();
}   
Copy
Find a Friend YouKn0wWho
GNU G++17
49 ms
5.3 MB
Accepted