代码如下:
#include<bits/stdc++.h>
typedef long long ll;
char buf[1<<21],*p1=buf,*p2=buf,obuf[1<<21],*O=obuf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
using namespace std;
inline ll read(){ll x=0,f=1;char c=getchar();while(c<48||c>57){if(c==45)f=0;c=getchar();}while(c>47&&c<58)x=(x<<3)+(x<<1)+(c^48),c=getchar();return f?x:-x;}
inline void write(ll x){if(x<0)putchar(45),x=-x;if(x>9)write(x/10);putchar(x%10+48);}
ll n,val[1000005],head[1000005],tot,b,x1,x2,ed,ans,f[1000005][2];
bool vis[1000005];
stack<ll>sta;
struct edge{ll to,nxt;}e[2000005];
inline void add(ll u,ll v){
e[++tot]=(edge){v,head[u]};
head[u]=tot;
}
inline void dfs1(ll x,ll pre){
vis[x]=1;
for(ll i=head[x];i;i=e[i].nxt){
if(e[i].to==pre)continue;
if(vis[e[i].to]){
x1=x,x2=e[i].to,ed=i;
continue;
}
dfs1(e[i].to,x);
}
}
inline void dfs2(ll x,ll pre){
f[x][0]=0,f[x][1]=val[x];
for(ll i=head[x];i;i=e[i].nxt){
if(e[i].to==pre)continue;
if((x1==x&&x2==e[i].to)||(x1==e[i].to&&x2==x)){
continue;
}
dfs2(e[i].to,x);
f[x][1]+=f[e[i].to][0];
f[x][0]+=max(f[e[i].to][1],f[e[i].to][0]);
}
}
signed main(){
n=read();
for(ll i=1;i<=n;++i){
val[i]=read(),b=read(),add(b,i),add(i,b);
}
for(ll i=1;i<=n;++i){
if(vis[i])continue;
dfs1(i,-2);
dfs2(x1,-1);
ll tmp=f[x1][0];
dfs2(x2,-1);
ans+=max(tmp,f[x2][0]);
}
printf("%lld",ans);
return 0;
}