Source Code
#include <bits/stdc++.h>
#define ll  long long
#define ss second
#define ff first
#define sz size()
#define el '\n'
#define tc ll tt; cin>>tt; while(tt--)
using namespace std;

void fastIO() {
	ios::sync_with_stdio(false);
	cout.tie(nullptr);
	cin.tie(nullptr);
}
const ll N = 2e5 + 5;
vector<ll> s[N],ps(N),temp(N);

bool dfs(ll i,ll n,ll t){
    if (t == 0){
        if (temp[i] == 0 || abs(ps[temp[i]] - ps[i]) > abs(ps[n] - ps[i]))
            temp[i] = n;
        return 1;
    }
    ll f = 0,ans = 0;
    for (auto x : s[n]){
        f |= dfs(i,x,t - 1);
    }
    return f;
}

int main(){
    fastIO();
    ll n;
    cin >> n;
    ll res[N];
    for (int i = 2;i <= n;i++){
        ll x;
        cin >> x;
        s[x].push_back(i);
    }
    for (int i = 1;i <= n; i++) cin >> ps[i];
    for (int i = 1;i <= n;i++){
        if (dfs(i,i,4))
            res[i] = temp[i];
        else
            res[i] = 0;
    }
    res[n] = 0;
    for (int i = 1;i <= n;i++)
        cout << res[i] << ' ';
}
Copy
Find a Friend heba.daraghmeh
GNU G++17
137 ms
17.1 MB
Accepted