Source Code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int p[1000000];
int ans[1000000];
int val[1000000];
int best[1000000];
int main() {
    ios_base::sync_with_stdio(0);
    int n;
    cin>>n;
    best[1] = 2000000000;
    for (int i=2;i<=n;i++) {
        cin>>p[i];
        best[i] = 2000000000;
    }
    for (int i=1;i<=n;i++) {
        cin>>val[i];
        int d = p[p[p[p[i]]]];
        if (d!=0) {
            int cur = abs(val[i]-val[d]);
            if (cur < best[d]) best[d]=cur, ans[d] = i;
        }
    }
    for (int i=1;i<=n;i++) {
        cout<<ans[i];
        if (i+1<=n) cout<<' ';
        else cout<<endl;
    }
}
Copy
Find a Friend RedNextCentury
GNU G++17
67 ms
5.3 MB
Accepted