Source Code
/**
It falls to me to inform you that this one is in the bag
**/

#include <bits/stdc++.h>
#include <chrono>
#include <random>
#define ll long long
#define ld long double
#define pb push_back
#define pii pair<int,int>
#define pll pair<long long,long long>
#define F first
#define S second
#define all(a) a.begin(),a.end()

using namespace std;

const ll Mod=1e9+7 ;

ll poww(ll a,ll b,ll mod=Mod){
    ll res=1;if(b<0||b>=Mod)b=(b%(mod-1)+mod-1)%(mod-1);
    for(;b;b>>=1,a=1ll*a*a%mod)
      if(b&1)res=1ll*res*a%mod;
    return res;
}
template <typename T>
void Max(T& x,T y){
x=max(x,y);
}
template <typename T>
void Min(T& x,T y){
x=min(x,y);
}
void OK(bool yes){
    cout<<(yes?"YES\n":"NO\n");
}

const ll LN=(1<<24),K=77,inf=3e18,Mod1=1e9+7,Mod2=999997457;
const ld pi=acos(-1),eps=1e-12;
const int N=500300,M=2020,NN=2000100;
ll Fact[NN],iFact[NN];

void init(){
Fact[0]=iFact[0]=1ll;
for(ll i=1;i<NN;i++)Fact[i]=(1ll*Fact[i-1]*i)%Mod;
iFact[NN-1]=poww(Fact[NN-1],-1,Mod);
for(ll i=NN-2;i>=0;i--)iFact[i]=(1ll*iFact[i+1]*(i+1))%Mod;
}
ll inv(ll x,ll y=-1){
    return poww(x,y,Mod);
}
ll Cnk(ll x,ll y){
if(y > x||x < 0||y < 0)return 0;
return (  ((Fact[x]*poww(Fact[y],-1,Mod))%Mod)  *poww(Fact[x-y],-1,Mod))%Mod;
}
template<typename T>
void Add(T& x,T y){
x%=Mod;
y%=Mod;
if(x<0)x+=Mod;
if(y<0)y+=Mod;
x=(x+y>=Mod?x+y-Mod:x+y);
//x+=y;
}

template<typename T>
void Mul(T& x,T y){
x%=Mod;
y%=Mod;
x=x*y;
x%=Mod;
if(x<0)x+=Mod;
}

void ask(int x,int y){
    cout<<"? "<<x<<' '<<y<<endl;
}
void ask(int x){
    cout<<"? "<<x<<endl;
}

int X[4]={-1,0,+1,0};
int Y[4]={0,-1,0,+1};
string str="ULDR";
string rts="DRUL";

ll Ans[N],val[N],par[N],idx[N];

void upd(ll nd){
    bool f=1;
    int cnt=4,x=nd;
    while(cnt--){
        x=par[x];
        if(x==-1)break;
    }
    if(cnt==-1){
        if(abs(val[nd]-val[x])<Ans[x]){
            Ans[x]=abs(val[nd]-val[x]);
            idx[x]=nd;
        }
        else if(abs(val[nd]-val[x])==Ans[x]){
            Min(idx[x],nd);
        }
    }
}


int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    //freopen("win.in","r",stdin);

    int T=1;
    int Case=1;


    //init();
    //cin>>T;
    while(T--){
        int n;
        cin>>n;
        par[1]=-1;
        for(int i=2;i<=n;i++)cin>>par[i];
        for(int i=1;i<=n;i++)cin>>val[i];
        for(int i=1;i<=n;i++){
            Ans[i]=inf;
            idx[i]=0;
            upd(i);
        }
        for(int i=1;i<=n;i++)cout<<idx[i]<<' ';
        cout<<'\n';
    }

    return 0;
}

/**
1
6
3 2 5 6 1 4

*/

/**

*/
Copy
Find a Friend Wise-ard
GNU G++17
51 ms
8.5 MB
Accepted