样例过了
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e6+5;
const int MANX=1e7;
vector<int> G[N];
int f[N],val[N],mark;
ll dp[N][2];
bool vis[N];
void add(int from,int to){
G[from].push_back(to);
f[to]=from;
}
void dfs(int u){
dp[u][0]=0;
dp[u][1]=val[u];
vis[u]=true;
for(int v : G[u]){
if(v==mark) continue;
dfs(v);
dp[u][1]+=dp[v][0];
dp[u][0]+=max(dp[v][0],dp[v][1]);
}
}
int check(ll op){
vis[op]=true;
int fa=f[op];
if(vis[fa]) return fa;
else check(fa);
}
ll solve(int u){
ll res=0;
mark=check(u);
dfs(mark);
res=max(res,dp[mark][0]);
mark=f[mark];
dfs(mark);
res=max(res,dp[mark][0]);
return res;
}
int main(){
ios::sync_with_stdio(false);
memset(vis,0,sizeof(vis));
int n;
cin>>n;
for(int i=1;i<=n;i++){
int d;
cin>>val[i]>>d;
add(d,i);
}
ll ans=0;
for(int i=1;i<=n;i++){
if(!vis[i]){
ans+=solve(i);
}
}
cout<<ans;
return 0;
}