#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<pair<int, int>> g[n+1];
    for(int i=1;i<=n;i++){
        g[i].push_back({p[i], w[i]});
        g[p[i]].push_back({i, w[i]});
    }
    multiset<int> skup;
    for(auto u:g[1]) skup.insert(-u.second);
    for(int i=1;i<=q;i++){
        skup.erase(-w[s[i]]);
        skup.insert(-k[i]);
        int tri = 3;
        int zbir = 0;
        for(auto u:skup){
            if(tri>0){
                zbir+=(-u);
                tri--;
            }
        }
        ans[i] = zbir;
    }
}