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

const int MAXN = 2e5 + 1, oo = 2e9;
int n, m[MAXN], p[MAXN];
vector<int> g[MAXN], ans, val;

void TandH(int org, int node, int mngr) {
  if(mngr == 4) { 
    if(abs(p[node] - p[org]) < val[org]) {
      ans[org] = node;
      val[org] = abs(p[node] - p[org]);
    }
    return ;
  }
  for(auto i : g[node]) {
    TandH(org, i, mngr + 1);
  }
}
void solve() {
  cin >> n;
  ans.resize(n + 1), val.resize(n + 1, oo);
  for(int i = 2; i <= n; i++) {
    cin >> m[i];
    g[m[i]].push_back(i);
  }
  for(int i = 1; i <= n; i++) {
    cin >> p[i];
  }
  for(int i = 1; i <= n; i++) {
    TandH(i, i, 0);
  }
  for(int i = 1; i <= n; i++) {
    cout << ans[i] << ' ';
  }
}
 
int main(){ 
  #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
  #endif
  ios::sync_with_stdio(0);
  cin.tie(0);
  int TC = 1;   
  // cin >> TC;
  while(TC--) {
    solve();
  }
  return 0;
}
Copy
Find a Friend Ammar_Lahloh
GNU G++17
136 ms
15.5 MB
Accepted