dalao求调
#include <bits/stdc++.h>
#define int long long
#define DB double
using namespace std;
const int N = 1e6 + 10, INF = 1e15;
int n, root, ans;
int val[N], dp[N][2], fa[N];
bool vis[N];
vector <int> v[N];
void dfs(int x)
{
dp[x][0] = 0;
dp[x][1] = val[x];
vis[x] = true;
for(auto y : v[x])
{
if(y != root)
{
dfs(y);
dp[x][0] += max(dp[y][0], dp[y][1]);
dp[x][1] += dp[y][0];
}
else dp[y][1] = -INF;
}
}
void findcircle(int x)
{
vis[x] = true;
root = x;
while(vis[root] == false)
root = fa[root], vis[root] = true;
dfs(root);
int t = max(dp[root][0], dp[root][1]);
root = fa[root];
dfs(root);
ans += max({t, dp[root][0], dp[root][1]});
return ;
}
int read()
{
char a = getchar();
while(a < '0' || a > '9')
a = getchar();
int t = 0;
while(a <= '9' && a >= '0')
{
t = (t << 1) + (t << 3) + a - '0';
a = getchar();
}
return t;
}
signed main()
{
n = read();
// scanf("%lld", &n);
int x;
for(int i = 1; i <= n; i ++ )
{
val[i] = read(), x = read();
// scanf("%lld%lld", &val[i], &x);
v[x].push_back(i);
fa[i] = x;
}
for(int i = 1; i <= n; i ++ )
{
if(!vis[i])
findcircle(i);
}
printf("%lld", ans);
return 0;
}