#include<bits/stdc++.h>
#define int long long
#define up(i,l,r) for(int i=l; i<=r; ++i)
#define dn(i,r,l) for(int i=r; i>=l; --i)
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
using namespace std;
inline int max(int a,int b,int c) { return max(max(a,b),c); }
const int N=1000005;
int n, w[N], Rt, X, Y, out[N];
int f[N][2], g[N][2], Ans; bool vis[N], tag[N];
vector<int> F[N]; map<pii,int> qwq;
void split(int x) {
if(!out[x]) return;
if(tag[out[x]]) X=x, Y=out[x];
else tag[out[x]]=1, split(out[x]);
}
void dp(int x) {
if(x==Y) { f[x][1]=w[x]; }
else { f[x][1]=g[x][1]=w[x]; }
for(int y:F[x]) if(!vis[y]) {
if(x==X&&y==Y||y==X&&x==Y) continue;
vis[y]=1, dp(y);
f[x][0]+=max(f[y][0],f[y][1]);
g[x][0]+=max(g[y][0],g[y][1]);
f[x][1]+=f[y][0], g[x][1]+=g[y][0];
}
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
up(i,1,n) {
cin >> w[i] >> out[i];
F[i].pb(out[i]), F[out[i]].pb(i);
++qwq[mp(i,out[i])];
++qwq[mp(out[i],i)];
}
up(i,1,n) if(!vis[i]) {
X=Y=0, tag[i]=1, split(i);
if(qwq[mp(X,Y)]==2) X=Y=0;
if(X|Y) vis[X]=1, dp(X), Ans+=max(f[X][0],g[X][0],g[X][1]);
else vis[i]=1, dp(i), Ans+=max(f[i][0],f[i][1]);
}
cout << Ans;
return 0;
}