Source Code
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <iostream>
#define F first
#define S second
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define p_b push_back
#define all(c) c.begin(), c.end()
#define mem(array, some_data) memset(array, some_data, sizeof array);
using namespace std;
using namespace __gnu_pbds;
typedef long long ll; //printf("%lld ", ll); to out put long
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef tree<int ,null_type,less<int >,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
const double eps = 1e-6;
const int MAXN = 2e5 + 3;
const ll MOD = 1e9 + 7;
const ll INF = 1e18;
bool ODD(ll O)
{
    return (O % 2 != 0);
}

ll lcm(ll a, ll b)
{
    return a * b / __gcd(a, b);
}
int dx[] = {1, 0, -1, 0,-1, 1, -1, 1};
int dy[] = {0, 1, 0, -1,-1, 1, 1, -1};

bool is_power_of_2(int x) {
    if(x == 0) return true;
    return (ceil(log2(x)) == floor(log2(x)));
}
/*------ never give up --------*/
vector <int> adj[MAXN];
int prs[MAXN];
int bfs(int u, int n) {
    int dis[n + 3] = {};
    set <pii> st;
    queue <int> q;
    q.push(u);
    dis[u] = 0;
    int bst_prs = 1e9 + 5, ret = MAXN;
    while(!q.empty()) {
        int cur = q.front();
        q.pop();
        for(int v : adj[cur]) {
            if(dis[cur] == 3) {
                int diff = abs(prs[cur] - prs[v]);
                if(diff < bst_prs) {
                    ret = v;
                    bst_prs = diff;
                }
                if(diff == bst_prs) {
                    ret = min(ret , v);
                }
                continue;
            }
            dis[v] = dis[cur] + 1;
            q.push(v);
        }
    }
    if(ret == MAXN) return 0;
    return ret;
}


void solve(int test_case)
{

    int n;
    cin >> n;
    for(int i = 2; i <= n; i++) {
        int x;
        cin >> x;
        adj[x].push_back(i);
    }
    for(int i = 1; i <= n; i++) {
        cin >> prs[i];
    }
    for(int i = 1; i <= n; i++) {
        cout << bfs(i, n) << " ";
    }
    for(int i = 0; i <= n; i++) adj[i].clear();

}
int main()
{

    //ios_base::sync_with_stdio(0); cin.tie(0);
    int n = 1;
    //cin >> n;

    while (n--)
    {

        solve(n);
    }

    return 0;
}
Copy
Find a Friend OBITO
GNU G++17
8 ms
5.3 MB
Wrong Answer