#include <bits/stdc++.h>
using namespace std;

const int N = 200005;
vector < pair < int , int > > g[N];
pair < long long , long long > mx[N];
pair < long long , long long > xm[N];
long long res[N];

void bld(int p, int pret)
{
  for(auto it : g[p]) if(it.first != pret) bld(it.first, p);
  for(auto it : g[p])
  {
    int q = it.first; int w = it.second;
    if(q == pret) continue;
    if(mx[q].first + w > mx[p].first)
    {
      xm[p].first = mx[p].first;
      xm[p].second = mx[p].second;
      mx[p].first = mx[q].first + w;
      mx[p].second = q;
    }
    else if(mx[q].first + w > xm[p].first)
    {
      xm[p].first = mx[q].first + w;
      xm[p].second = q;
    }
  }
}
void dfs(int p, int pret, long long up)
{
  res[p] = 0;
  long long thr = 0;
  for(auto it : g[p])
  {
    if(it.first == pret) continue;
    if(it.first != mx[p].second && it.first != xm[p].second) thr = max(mx[it.first].first + it.second, thr);
  }
  if(mx[p].second != 0 && xm[p].second != 0)
  {
    if(thr != 0) res[p] = max(res[p], thr + mx[p].first + xm[p].first);
    if(up != 0) res[p] = max(res[p], up + mx[p].first + xm[p].first);
  }

  for(auto it : g[p])
  {
    int q = it.first; int w = it.second;
    if(q == pret) continue;
    if(q == mx[p].second) { dfs(q, p, max(up, xm[p].first) + w); continue; }
    dfs(q, p, max(up, mx[p].first) + w);
  }
}
void Bumerang(int n, int q, int* p, int* w, int* s, int* k, long long* ans)
{
  if((long long)n * q > 25000000) return;
  for(int i = 2; i <= n; i++)
  {
    g[i].push_back(make_pair(p[i], w[i]));
    g[p[i]].push_back(make_pair(i, w[i]));
  }

  for(int x = 1; x <= q; x++)
  {
    for(int i = 0; i < g[s[x]].size(); i++) if(g[s[x]][i].first == p[s[x]]) g[s[x]][i].second = k[x];
    for(int i = 0; i < g[p[s[x]]].size(); i++) if(g[p[s[x]]][i].first == s[x]) g[p[s[x]]][i].second = k[x];

    for(int i = 0; i < n + 3; i++) res[i] = mx[i].first = mx[i].second = xm[i].first = xm[i].second = 0;

    bld(1, 0);
//    for(int i = 1; i <= n; i++)
//    {
//      cout << i << ": ";
//      for(auto it : g[i]) cout << "{ " <<  it.first << ", " << it.second  << " }, ";
//      cout << "\n";
//    }
//    for(int i = 1; i <= n; i++) cout << "{ " <<  mx[i].first << ", " << mx[i].second  << " }, { " <<  xm[i].first << ", " << xm[i].second  << " } |\n";
//    cout << "\n";
    dfs(1, 0, 0);

    ans[x] = 0;
    for(int i = 1; i <= n; i++) ans[x] = max(ans[x], res[i]);
  }
}