Source Code
#include <bits/stdc++.h>
#include<unordered_map>
using namespace std;
#define ll long long 
vector<ll>p(0);
ll power(ll a, ll b)
{
    if (b == 0) return 1;
    ll tmp = power(a, b / 2);
    ll result = tmp * tmp;
    if (b % 2 == 1)result *= a;
    return result;
}
ll binarySearch(ll left, ll right, ll key, vector<ll>v)
{
    ll mid = (right + left) / 2;
    if (left <= right)
    {

        if (key == v[mid])
        {
            return mid;
        }
        if (v[mid] < key)
            return binarySearch(mid + 1, right, key, v);
        if (v[mid] > key)
            return binarySearch(left, mid - 1, key, v);
    }
    return mid;
}
void sol(vector<vector<int>>v,int count,pair<ll,int> &ans,int m,ll int g)
{
    if (count == 0)
        {
            if (ans.first > abs(p[g] - p[m]))
            {
                ans.first = abs(p[g] - p[m]);
                ans.second = m;
            }

        }
    else
    for (int i = 0; i < v[m].size(); i++)
    {
        sol(v,count-1, ans, v[m][i], g);
    }
    if (count == 4)
        cout << ans.second <<" ";
}
void dfs(vector<vector<int>>v)
{
   
    for (int i = 1; i < v.size(); i++)
    {
        pair<ll, int>ans = { LLONG_MAX,0 };
        sol(v, 4,ans,i,i);
    }
}

int main() { 
    ll n;
    cin >> n;
    vector<vector<int>>v(n+1);
    p.resize(n+1);
    for (int i = 2; i <= n; i++)
    {
        int m;
        cin >> m;
        v[m].push_back(i);
    }
    for (int i = 1; i <= n; i++)
        cin >> p[i];
    dfs(v);

}
Copy
Find a Friend Falcon-64
GNU G++17
2057 ms
5.1 MB
Time Limit Exceeded