#include <iostream>
#include <vector>
#include <map>
#define ll long long
using namespace std;
vector <vector<int>> g;
map <pair<int, int>, int> mapa;
vector <bool> diamv;
ll maxdist, maxc;
void dfs(int st, int p, ll dist)
{
    if (dist >= maxdist)
    {
        maxdist = dist;
        maxc = st;
    }
    for (auto i : g[st])
    {
        if (i != p) dfs(i, st, dist + mapa[{st, i}]);
    }
}
bool dfs1(int st, int p, int en)
{
    diamv[st] = true;
    if (st == en) return true;
    for (auto i : g[st])
    {
        if (i != p)
        {
            if (dfs1(i, st, en)) return true;
        }
    }
    return false;
}
void dfs2(int st, int p, ll dist)
{
    if (dist >= maxdist) maxdist = dist;
    for (auto i : g[st])
    {
        if (i != p && !diamv[i]) dfs2(i, st, dist + mapa[{st, i}]);
    }
}
void Bumerang(int n, int q, int* p, int* w, int* s, int* k, long long* ans)
{
    g.resize(n);
    for (int i = 0; i < n; i++)
    {
        p[i] = p[i + 1];
        p[i]--;
        s[i] = s[i + 1];
        s[i]--;
    }
    for (int i = 0; i < n; i++) w[i] = w[i + 1];
    for (int i = 0; i < n; i++)
    {
        if (p[i] == -1) continue;

        g[i].push_back(p[i]);
        g[p[i]].push_back(i);
        mapa[{i, p[i]}] = w[i];
        mapa[{p[i], i}] = w[i];
    }
    int cnt = 0;
    q = 1;
    while (q--)
    {
        mapa[{s[cnt], p[s[cnt]]}] = k[cnt+1];
        mapa[{p[s[cnt]], s[cnt]}] = k[cnt+1];
        maxdist = 0; maxc = -1;
        dfs(0, -1, 0);
        int a = maxc;
        maxdist = 0; maxc = -1;
        dfs(a, -1, 0);
        int b = maxc;
        diamv.assign(n, false);
        dfs1(a, -1, b);
        ll diam = maxdist;
        ll maxxovde = 0;
        for (int i = 0; i < n; i++)
        {
            if (diamv[i])
            {
                maxdist = 0;
                dfs2(i, -1, 0);
                maxxovde = max(maxxovde, maxdist);
            }
        }
        ans[cnt] = diam + maxxovde;
        cnt++;
    }
}