#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define maxn 1000005
#define ll long long
using namespace std;
struct node
{
ll to,next;
}g[maxn*2];
ll tot,head[maxn];
void addedge(ll u,ll v)
{
g[tot].to=v;
g[tot].next=head[u];
head[u]=tot++;
}
ll n,ban[2],vis[maxn],val[maxn],f[2][maxn],bj,use,ans,p,num,E;
void dfs1(ll u,ll pre)
{
//printf("%d\n",u);
ll v,i;
vis[u]=1;
for(i=head[u];i!=-1;i=g[i].next)
{
v=g[i].to;
if((i^1)==pre)
continue;
if(vis[v])
{ban[0]=u;ban[1]=v;vis[v];E=i;continue;}
dfs1(v,i);
}
}
void dfs2(ll u,ll pre)
{
// printf("%d %d %d\n",u,ban[use],ban[use^1]);
//p++;
//if(p>=4)
//return ;
ll v,i,ans1=0,ans0=0;
for(i=head[u];i!=-1;i=g[i].next)
{
v=g[i].to;
if((i^1)==pre)
continue;
if (i==E||(i^1)==E)
continue;
dfs2(v,i);
ans1+=f[0][v];
ans0+=max(f[0][v],f[1][v]);
}
f[0][u]=ans0;
f[1][u]=ans1+val[u];
}
int main()
{
ll i,x;
scanf("%lld",&n);
memset(head,-1,sizeof(head));
for(i=1;i<=n;i++)
{
scanf("%lld%lld",&val[i],&x);
addedge(i,x);
addedge(x,i);
}
for(i=1;i<=n;i++)
{
if(!vis[i])
{
dfs1(i,-2);
// printf("%lld %lld\n",ban[0],ban[1]);
use=0;
// printf("%d %d\n",ban[0],ban[1]);
// scanf("%d",&x);
memset(f,0,sizeof(f[1]));
dfs2(ban[1],-1);
ans=f[0][ban[1]];
use++;
memset(f,0,sizeof(f[1]));
dfs2(ban[0],-1);
ans=max(ans,f[0][ban[0]]);
num+=ans;
//printf("%lld",ans);
}
}
if(n==1)
num=3;
printf("%lld",num);
}