学习自https://www.luogu.org/blog/user52918/qian-tan-ji-huan-shu
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<stack>
#include<cstring>
#include<set>
#include<iterator>
#include<list>
#include<deque>
#include<queue>
#include<map>
#include<cmath>
#include<sstream>
#include<cstdio>
#include<ctime>
#include<iomanip>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
using namespace std;
const int N = 1e6 + 10;
typedef long long ll;
typedef pair<int, int> P;
int head[N], ver[2 * N], Next[2 * N];
ll edge[2 * N];
int q[2 * N];
ll f[N], dist[2 * N], cr[2 * N];
ll dis[N];
int tot, num;
int bel[N];
int deg[N];
int vis[N];
void addedge(int x, int y, int z)
{
ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot, deg[y]++;
}
void dfs(int x)
{
bel[x] = num;
for (int i = head[x]; i; i = Next[i])
{
int y = ver[i];
if (!bel[y])
{
//printf("%d ---> %d\n", x, y);
dfs(y);
}
}
}
int n;
void topsort()
{
int l = 0, r = 0;
for (int i = 1; i <= n; i++)
{
if (deg[i] == 1)
q[++r] = i;
}
while (l < r)
{
int x = q[++l];
for (int i = head[x]; i; i = Next[i])
{
int y = ver[i];
if (deg[y] > 1)
{
//cout << x << "--->" << y << endl;
deg[y]--;
dist[bel[x]] = max(dist[bel[x]], f[x] + f[y] + edge[i]);
f[y] = max(f[y], f[x] + edge[i]);
if (deg[y] == 1)
q[++r] = y;
}
}
}
}
void dp(int t, int x)
{
int m = 0, i, y = x;
do
{
cr[++m] = f[y], deg[y] = 1;
for (i = head[y]; i; i = Next[i])
{
if (deg[ver[i]] > 1)
{
dis[m + 1] = dis[m] + edge[i];
y = ver[i];
break;
}
}
} while (i);
/*cout << "------" << endl;
for (int i = 1; i <= m; i++)
{
cout << dis[i] << " ";
}
cout << endl;
cout << "-----" << endl;*/
if (m == 2)
{
ll l = 0;
for (int i = head[y]; i; i = Next[i])
{
if (ver[i] == x)
{
l = max(l, edge[i]);
}
}
dist[t] = max(dist[t], f[x] + f[y] + l);
return;
}
for (int i = head[y]; i; i = Next[i])
{
if (ver[i] == x)
{
dis[m + 1] = dis[m] + edge[i];
break;
}
}
for (int i = 1; i <= m; i++)
{
cr[i + m] = cr[i];
dis[i + m] = dis[m + 1] + dis[i];
}
int l = 1, r = 0;
q[++r] = 1;
for (int i = 2; i < 2 * m; i++)
{
while (l <= r && i - q[l] >= m)
{
l++;
}
dist[t] = max(dis[i] - dis[q[l]] + cr[i] + cr[q[l]], dist[t]);
while (l <= r && cr[q[r]] - dis[q[r]] <= cr[i] - dis[i])
{
r--;
}
q[++r] = i;
}
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
int x, y;
scanf("%d%d", &x, &y);
addedge(i, x, y);
addedge(x, i, y);
}
for (int i = 1; i <= n; i++)
{
if (!bel[i])
{
num++;
dfs(i);
}
}
topsort();
ll ans = 0;
for (int i = 1; i <= n; i++)
{
if (deg[i] > 1 && !vis[bel[i]])
{
vis[bel[i]] = 1;
dp(bel[i], i);
ans += dist[bel[i]];
}
}
printf("%lld\n", ans);
return 0;
}