Source Code

#include <bits/stdc++.h>
#define ll long long
using namespace std;

int main()
{
      ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    ll n;cin>>n;
   pair<ll,ll>a[n];
   a[0].first=1;
    for(int i=1;i<n;i++)
    cin>>a[i].first;
    for(int i=0;i<n;i++)cin>>a[i].second;
    pair<ll,pair<ll,ll>>le[n];le[0]={1,{a[0].second,1}};
    for(int i=1;i<n;i++){
        le[i]={le[a[i].first-1].first+1,{a[i].second,i+1}};
       
    }
   sort(a,a+n);
 
   for(int i=0;i<n;i++){  ll x=-1,y=-1;
       for(int j=i+1;j<n;j++){
           if(le[j].first-le[i].first==4)
           if(x==-1)
           x=le[j].second.second,y=abs(le[j].second.first-le[i].second.first);
           else
           {
               if(abs(le[j].second.first-le[i].second.first)<y)
               x=le[j].second.second,y=abs(le[j].second.first-le[i].second.first);
           }
           
       }
       if(x>-1)
       cout<<x<<" ";
       else
       cout<<0<<" ";
   }
    
    
    return 0;
}
Copy
Find a Friend ateeq
GNU G++17
3 ms
792 KB
Wrong Answer