#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int a[N], b[N], rankk[N];
map<int,vector<pair<int, int>>>mp;
int main() {
int n;
cin>>n;
a[1] = 0;
for (int i = 2; i <= n; ++i) {
cin>>a[i];
}
for(int i = 2; i <= n; ++i) {
rankk[i] = rankk[a[i]]+1;
}
for (int i = 1; i <=n; ++i) {
cin>>b[i];
}
for (int i = 1; i <= n; ++i) {
mp[rankk[a[i]]].push_back({b[i], i});
}
for (int i = 1; i <= n; ++i) {
if (mp.find(i) != mp.end()) {
sort(mp[i].begin(), mp[i].end());
}
}
vector<int> ans;
for (int i = 1; i <= n; ++i) {
if(mp.find(rankk[i]) == mp.end() || mp.find(rankk[i]+3) == mp.end()) {
ans.push_back(0);
}else {
// cout<<i<<" "<<rankk[i]<<" "<<mp[rankk[i]+3].size()<<endl;
// for(auto w : mp[rankk[i]+3] )
// cout << w.first <<" " << w.second <<" ";
// cout <<"\n";
pair<int,int> tmp = make_pair(b[i],-1);
auto up = lower_bound(mp[rankk[i]+3].begin(), mp[rankk[i]+3].end(), tmp);
auto low = up;
pair<int, int> x = {-1, -1};
if(up != mp[rankk[i]].end()) {
x = make_pair(abs(up->first - b[i]), up->second);
// cout<<"up: "<<up->second<<endl;
}
if (low != mp[rankk[i]].begin()){
--low;
if (abs((low -> first) - b[i]) < x.first ) {
x = make_pair(abs((low -> first) - b[i]), low->second);
}
// cout<<"low: "<<low->second<<endl;
}
ans.push_back(x.second);
}
}
/* for (auto i : mp) {
int x = i.first;
vector<pair<int, int>> y = i.second;
cout<<x<<" "<<endl;
for (int j = 0; j<y.size(); ++j) {
int emp
cout<<y[j].first<<" "<<y[j].second<<endl;
rank[y[j].first] = rank[x]+1;
}
}
*/
cout<<ans[0];
for (int i = 1; i< ans.size(); ++i) {
cout<<" "<<ans[i];
}
puts("");
return 0;
}
Copy