#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<vector<int>> adj(n);
    for(int i = 2; i <= n; i++){
        adj[i-1].push_back(p[i]-1);
        adj[p[i]-1].push_back(i-1);
    }
    /*cout << "adj\n";
    for(int i = 0; i < n; i++){
        for(int j = 0; j < adj[i].size(); j++)
        {
            cout << adj[i][j] << " ";
        }
        cout << "\n";
    }
    cout << "\n\n\n";
*/
    bool check = false,check2 = false;
    for(int i = 0; i < n; i++){
        if(adj[i].size() > 1 && !check){
            check = true;
        }else if(adj[i].size() > 1 && check){
            check2 = true;
            break;
        }

    }



    if(check && !check2){
        vector<pair<int,int>> kur;
        for(int i = 0; i < n; i++){
            kur.push_back({w[i+1],i+1});
        }



        vector<pair<int,int>> om = kur;
        sort(om.begin(),om.end(),greater<pair<int,int>>());
        vector<pair<int,int>> vec(3);
        vec[0] = om[0];
        vec[1] = om[1];
        vec[2] = om[2];
        //cout << vec[0].first << " " << vec[1].first << " " << vec[2].first << '\n';

        for(int i = 0; i < q; i++){
            kur[s[i+1]-1].first = k[i+1];
            if(kur[s[i+1]-1].second == vec[0].second || kur[s[i+1]-1].second == vec[1].second || kur[s[i+1]-1].second == vec[2].second){
                if(kur[s[i+1]-1].second == vec[0].second)vec[0] = kur[s[i+1]-1];
                if(kur[s[i+1]-1].second == vec[1].second)vec[1] = kur[s[i+1]-1];
                if(kur[s[i+1]-1].second == vec[2].second)vec[2] = kur[s[i+1]-1];
                for(int j = 0; j < om.size(); j++){
                    if(om[j].second == kur[s[i+1]-1].second){
                        om[j] = kur[s[i+1]-1];

                    }

                }
                sort(om.begin(),om.end(),greater<pair<int,int>>());
                vec[0] = om[0];
                vec[1] = om[1];
                vec[2] = om[2];


            }else{
                for(int j = 0; j < om.size(); j++){
                    if(om[j].second == kur[s[i+1]-1].second){
                        om[j] = kur[s[i+1]-1];

                    }

                }
                if(kur[s[i+1]-1].first > vec[2].first){
                    vec[2] = kur[s[i+1]-1];
                    sort(vec.begin(),vec.end(),greater<pair<int,int>>());
                }

            }

            //cout << vec[0].first << " " << vec[1].first << " " << vec[2].first << '\n';


            ans[i+1] = vec[0].first + vec[1].first + vec[2].first;

        }


    }





}

/*
6 3
0 1 1 1 1 1
0 3 4 5 2 1
5 4 2
10 1 8
*/