RT,WA+TLE,30pts
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef pair<pair<ll,ll>,ll> P3;
typedef pair<pair<ll,ll>,pair<ll,ll> >P4;
#define mkp make_pair
#define fi first
#define se second
// #define FastIO
// #define OIcontest
const ll mod=998244353;
const ll maxn=500005;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
inline ll maxx(ll a,ll b){ return a>b?a:b; }
inline ll minn(ll a,ll b){ return a<b?a:b; }
inline ll lowbit(ll x){ return x&-x; }
/*--------------head------------------*/
ll n,con[1000005];
struct Edge{
ll to,nxt;
}edge[1000005];
ll head[1000005],tot;
void add(ll u,ll v){
edge[++tot].to=v;
edge[tot].nxt=head[u];
head[u]=tot;
}
ll huan[1000005], hd=1, tp, vis[1000005], vis2[1000005],End;
ll link[1000005], tl;
void dfs(ll x){
if(End) return;
huan[++tp]=x;
for(ll i=head[x];i;i=edge[i].nxt){
ll y=edge[i].to;
if(End) return;
if(vis[y]){
End=1;
while(huan[hd]!=y) hd++;
return;
}
vis[y]=1;
if(End) return;
dfs(y);
if(End) return;
}
tp--;
}
ll dp[1000005][2], f[1000005][2];
void treedp(ll x){
dp[x][1]=con[x];
for(ll i=head[x];i;i=edge[i].nxt){
ll y=edge[i].to;
if(vis2[y]) continue;
treedp(y);
dp[x][1]+=dp[y][0];
dp[x][0]+=max(dp[y][0],dp[y][1]);
}
}
ll answer=0;
void doit(){
ll ans=0;
for(ll i=1;i<=tl;i++) vis2[link[i]]=1;
for(ll i=1;i<=tl;i++) treedp(link[i]);
for(ll i=1;i<=tl;i++){
f[i][0]=dp[link[i]][0]+max(f[i-1][0],f[i-1][1]);
f[i][1]=dp[link[i]][1]+f[i-1][0];
}
ans=f[tl][0];
f[1][1]=-1e18;
for(ll i=2;i<=tl;i++){
f[i][0]=dp[link[i]][0]+max(f[i-1][0],f[i-1][1]);
f[i][1]=dp[link[i]][1]+f[i-1][0];
}
ans=max(ans,max(f[tl][0],f[tl][1]));
answer+=ans;
}
void solve(){
n=read();
for(ll i=1,fa;i<=n;i++){
con[i]=read(), fa=read();
add(fa,i);
}
for(ll i=1;i<=n;i++){
if(!vis[i]){
vis[i]=1;hd=1, tp=0, tl=0;
dfs(i);
End=0;
for(ll i=hd;i<=tp;i++) link[++tl]=huan[i];
doit();
}
}
cout<<answer<<endl;
}
int main(){
#ifdef OIcontest
freopen(".in","r",stdin);
freopen(".out","w",stdout);
#endif
#ifndef FastIO
ios::sync_with_stdio(0); cin.tie(0), cout.tie(0);
#endif
ll T=1;
while(T--) solve();
return 0;
}
/*
是谁挥霍的时光啊,是谁苦苦的奢望啊
这不是一个问题,也不需要你的回答
No answer.
*/