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 = 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
4 ms
1.0 MB
Wrong Answer