Source Code
#include <iostream>
#include <vector>
#include <list>

using namespace std;

int main(){
    int n; cin >> n;

    vector<int> m(n+1, 1);
    for(int i = 2; i <= n; ++i)
        cin >> m[i];
    
    vector<int> p(n+1);
    for(int i = 1; i <= n; ++i)
        cin >> p[i];
    
    vector<list<int>> cand(n+1);
    for(int i = 1; i <= n; ++i){
        int t = m[m[m[i]]];
        if( t==1 ) t = 0;
        else t = m[t];
        cand[t].push_back(i);
    }

    for(int i = 1; i <= n; ++i){
        if( cand[i].empty() ){
            cout << "0 ";
        } else {
            int t = cand[i].front();
            int d = abs(p[i] - p[t]);

            for(auto c : cand[i])
                if( abs(p[i] - p[c]) < d )
                    t = c, d = abs(p[i]-p[c]); 
            cout << t << ' ';
        }
    } cout << endl;

	return 0;
}
Copy
Find a Friend Trainee
GNU G++17
208 ms
14.7 MB
Accepted