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

void Bumerang(int n, int q, int* p, int* w, int* s, int* k, long long* ans){
    vector<long long> maxoddece(n+1);
    vector<long long> maxodroditelja(n+1);
    vector<vector<int>> deca(n+1);
    vector<int>dubina(n+1);
    vector<vector<int>> nadubini(n+1);
    w[s[1]] = k[1];
    nadubini[1].push_back(1);
    dubina[1] = 1;
    int maxdubina = 1;
    for ( int i = 1 ; i <= n ; i++)
    {
        deca[p[i]].push_back(i);
        dubina[i] = dubina[p[i]]+1;
        nadubini[dubina[i]].push_back(i);
        maxdubina = max(maxdubina,dubina[i]);
    }
    for ( int i = 0 ; i < nadubini[maxdubina].size() ; i++)
        maxoddece[nadubini[maxdubina][i]] = 0;
    for ( int i = maxdubina - 1 ; i >= 1 ; i--)
    {
        for ( int j = 0 ; j < nadubini[i].size() ; j++)
        {
            maxoddece[nadubini[i][j]] = 0;
            for ( int k = 0; k < deca[nadubini[i][j]].size() ; k++)
            {
                maxoddece[nadubini[i][j]] = max(maxoddece[nadubini[i][j]],w[deca[nadubini[i][j]][k]] + maxoddece[deca[nadubini[i][j]][k]]);
            }
        }
    }
    maxodroditelja[1] = 0;
    for ( int i = 2 ; i <= maxdubina ; i++)
    {
        for ( int j = 0 ; j < nadubini[i].size() ; j++)
        {
            int posmatramo = nadubini[i][j];
            maxodroditelja[posmatramo] = w[posmatramo] + maxodroditelja[p[posmatramo]];
            for ( int k = 0; k < deca[p[posmatramo]].size() ; k++)
            {
                int dete = deca[p[posmatramo]][k];
                if ( dete != posmatramo)
                {
                    maxodroditelja[posmatramo] = max( maxodroditelja[posmatramo],w[dete] + maxoddece[dete]);
                }
            }
        }
    }
    multiset<long long> res;
    for ( int i = 0 ; i <= deca[1].size() ; i++)
    {
        int dete = deca[1][i];
        res.insert(w[dete] + maxoddece[dete]);
    }
    ans[1] += *next(res.begin(),0)+*next(res.begin(),1)+*next(res.begin(),2);
    for ( int i = 2 ; i <= n ; i++)
    {
        if ( deca[i].size() >= 2)
        {
            res.empty();
            for ( int j = 0 ; j <= deca[i].size() ; j++)
            {
                int dete = deca[i][j];
                res.insert(w[dete] + maxoddece[dete]);
            }
            res.insert(maxodroditelja[i]);
            ans[1] = max(ans[1],*next(res.begin(),0)+*next(res.begin(),1)+*next(res.begin(),2) );
        }
    }

    return;
}