#include <bits/stdc++.h>

using namespace std;

vector<vector<int>> v;
vector<long long> dp1, vma1, vma2, vma3, vp, vw;

void dfs1(int x) {
    dp1[x] = 0;
    for (int y : v[x]) {
        dfs1(y);
        long long c = dp1[y] + vw[y];
        dp1[x] = max(c, dp1[x]);
        if (c > vma1[x]) {
            swap(vma2[x], vma3[x]);
            swap(vma1[x], vma2[x]);
            vma1[x] = c;
        } else if (c > vma2[x]) {
            swap(vma2[x], vma3[x]);
            vma2[x] = c;
        } else if (c > vma3[x]) {
            vma3[x] = c;
        }
    }
}

void Bumerang(int n, int q, int* p, int* w, int* s, int* k, long long* ans) {
    vp.resize(n + 1);
    vw.resize(n + 1);
    v.resize(n + 1);
    dp1.resize(n + 1);
    for (int i = 1; i <= n; i++) {
        vp[i] = p[i];
        v[p[i]].push_back(i);
        vw[i] = w[i];
    }
    for (int i = 1; i <= q; i++) {
        dp1.clear();
        dp1.resize(n + 1);
        vma1.clear();
        vma2.clear();
        vma3.clear();
        vma1.resize(n + 1, -1);
        vma2.resize(n + 1, -1);
        vma3.resize(n + 1, -1);
        vw[s[i]] = k[i];
        dfs1(1);
        //for (int x : dp1)
        //    cout << x << " ";
        //cout << endl;
        long long a = 0;
        for (int j = 1; j <= n; j++) {
            long long c = 0, e = -1;
            if (j != 1) {
                if (vma1[p[j]] != dp1[j] + vw[j])
                    e = vma1[p[j]] + vw[j];
                else if (vma2[p[j]] != -1)
                    e = vma2[p[j]] + vw[j];
                e = max(vw[j], e);
            }
            //cout << vma1[j] << " " << vma2[j] << " " << vma3[j] << " " << e << endl;
            if (e != -1 and e > vma3[j]) {
                if (vma2[j] != -1)
                    c = vma1[j] + vma2[j] + e;
            } else if (vma3[j] != -1) {
                c = vma1[j] + vma2[j] + vma3[j];
            }
            //cout << c << endl;
            a = max(c, a);
        }
        ans[i] = a;
    }
}