#include <bits/stdc++.h>
using namespace std;
vector<bool>vis;
vector<int>dist,visina,listovi;
vector<vector<pair<int,int>>>adj;
vector<vector<int>>lca;
int tr,pocetni;
void dfs(int v, int* p){
    vis[v]=true;
    if(v==p[pocetni])tr=v;
    lca[pocetni][v]=tr;
    for(auto u :adj[v]){
        if(!vis[u.first]){
            dfs(u.first,p);
        }
    }
}
void distance(int v, int trdist, int trvisina){
    vis[v]=true;
    dist[v]=trdist;
    visina[v]=trvisina;
    for(auto u:adj[v]){
        if(!vis[u.first]){
            distance(u.first, trdist+u.second, trvisina+1);
        }
    }
}

void Bumerang(int n, int q, int* p, int* w, int* s, int* k, long long* ans){
    adj.resize(n+3);
    lca.resize(n+3,vector<int>(n+3));
    dist.resize(n+3);
    visina.resize(n+3);
    vis.assign(n+3,false);
    for(int i=1;i<n;i++){
        adj[i+1].push_back({p[i+1],w[i+1]});
        adj[p[i+1]].push_back({i+1,w[i+1]});
    }
    for(int i=1;i<=n;i++){
        for(auto x:adj[i]){
            vis.assign(n+3,false);
            vis[i]=true;
            tr=i;
            pocetni=i;
            dfs(x.first,p);
        }
    }
    vis.assign(n+3,false);
    distance(1,0,0);
    for(int i=1;i<=n;i++){
        if(adj[i].size()==1)
            listovi.push_back(i);
    }
    for(int i =1;i<=n;i++){
        int x2=s[i];
        for(auto x1:adj[x2]){
            if(x1.first==p[x2])x1.second=k[i];
        }
        distance(1,0,0);
        int mx=0;
        for(int j=1;j<=n;j++){
            vector<int>st;
            if(adj[j].size()>=3){
                for(auto x:listovi){
                    st.push_back(dist[x]);
                }
                sort(st.begin(),st.end());
                mx=max(mx,(st[n-1]+st[n-2]+st[n-3]));
            }
        }
        ans[i]=mx;
    }

}