Source Code
#include <bits/stdc++.h>
using namespace std;

int n;

vector<int> man;
vector<int> mn;
vector<int> ind;
vector<int> sc;

int get_man(int i){
	if(i>0)
		return man[i];
	else
		return i;
}
int main() {
	cin>>n;
	man.resize(n+1,0);
	mn.resize(n+1,-1);
	sc.resize(n+1,0);
	ind.resize(n+1,-1);
	for(int i=2;i<=n;i++){
		cin>>man[i];
	}
	for(int i=1;i<=n;++i){
		cin>>sc[i];
	}
	for(int i=1;i<n+1;++i){
		int mm = i;
		for(int k=0; k<4; k++){
			mm = get_man(mm);
		}
		if(mm == 0)
			continue;
		// cout<<"manager of "<<i<<" is "<<mm<<endl;
		// cout<<"sc[i] - sc [mm] = "<< sc[i] << " - "<<sc[mm]<<endl;
		if(mn[mm] == -1){
			mn[mm] = abs(sc[i]-sc[mm]);
			ind[mm] = i;
		}else if(mn[mm] > abs(sc[i]-sc[mm])){
			mn[mm] = abs(sc[i]-sc[mm]);
			ind[mm] = i;
		}
	}
	for(int i=1;i<n+1;++i){
		cout<<(ind[i]==-1?0:ind[i])<<" ";
	}
	cout<<endl;
	return 0;
}
Copy
Find a Friend Saq
GNU G++17
126 ms
5.3 MB
Accepted