Source Code
#include <bits/stdc++.h>

#define ll long long

#define endl "\n"

using namespace std;
int N = 2*100001 ;

vector < vector<int > > v(N) ;

map < int,int> rnk ;

map < int ,int > p ;

void bfs (int i , vector<int > &vex) {
bool visited[N] ;
queue<int > q ;
visited[i] = true;
q.push(i);
while(!q.empty()){
    int x = q.front() ;
    q.pop() ;

    for(int val : v[x]){

        visited[val]=true;
        q.push(val) ;
        if(rnk[val] == rnk[i]+4)
            vex.push_back(val);
    }
}

}

int getMin(int i , int it) {

vector <int > vex ;
bfs (i ,vex  );
int mn =INT_MAX ;
int ret = 0;

for(int i =0 ;i<vex.size() ;i++) {

    int x = vex[i] ;
    if(abs(p[x]-it)  < mn)
    {
        mn = abs(p[x]-it) ;
        ret = x ;
    }

}

return ret ;
}


int main() {
int n  ;cin>>n;
rnk[1]=0;
int mx = 0;
for(int i =2 ,x; i<=n ;i++) {
    cin>>x ;
    rnk[i] = rnk[x]+1 ;
    mx = max(mx ,  rnk[i]) ;
    v[x].push_back(i) ;
}
for(int i =1 ,x;i<=n ;i++) {
    cin>>x ;
    p[i]=x ;
}


for(int i =1 ; i<=n ;i++) {
    if(rnk[i]+4 >mx){
        cout << 0 << "  " ;
        continue;
    }
    int temp = getMin(i , p[i]);
    cout << temp <<" " ;

}


return 0 ; }
Copy
Find a Friend Alice07
GNU G++17
2081 ms
15.2 MB
Time Limit Exceeded