Source Code
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define p1 2*p
#define p2 p1+1
#define ll long long
#define pb push_back
#define LFT p1,L,Mid
#define pf push_front
#define Mid ((L+R)/2)
#define RGT p2,Mid+1,R
#define pi pair<int,int>
#define pii pair<pi,pi>
#define deb(x) cout<<#x<<"="<<x<<endl
#define go ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
const int N = 200200;
int ans[N],id[N],a[N],pa[N],n;
int main()
{
    go;
    cin>>n;
    for(int i=1;i<=n;i++)
        ans[i]=2e9;
    for(int i=2;i<=n;i++)
        cin>>pa[i];
    for(int i=1;i<=n;i++)
        cin>>a[i];
    for(int i=1;i<=n;i++)
    {
        int x=pa[pa[pa[pa[i]]]];
        if(x==0)
            continue;
        //ans[x]=min(ans[x],abs(a[x]-a[i]));
        if(ans[x]>abs(a[x]-a[i]))
        {
            ans[x]=abs(a[x]-a[i]);
            id[x]=i;
        }
        else if(ans[x]==abs(a[i]-a[x]) && (id[x]==0 || id[x]>i))
            id[x]=i;
    }
    for(int i=1;i<=n;i++)
        cout<<id[i]<<' ';
    return 0;
}
Copy
Find a Friend Grapeee
GNU G++17
69 ms
5.3 MB
Accepted