#1和#10tle了,感觉应该哪里是哪里死循环
#include<iostream>
using namespace std;
#include<cstdio>
#define ll long long
template<typename T>
T max(T& x,T& y)
{
return x>y?x:y;
}
inline int qread()
{
int s=0,w=1;
char ch=getchar();
while(ch<'0' || ch>'9') {
if(ch=='-') w=-1;
ch=getchar();
}
while(ch>='0' && ch<='9') {
s=s*10+ch-'0';
ch=getchar();
}
return s*w;
}
struct Edge
{
int from,to,nex;
ll dis;
}edge[2000050];
int tot,head[1000050];
void add(int u,int v,ll d)
{
edge[++tot]={u,v,head[u],d};
head[u]=tot;
}
int n;
int s[1000010];
ll a[1000010];
bool vis[1000010];
int root;
void findrt(int u)
{
vis[u]=true;
if(vis[s[u]])
{
root=s[u];
}
else findrt(s[u]);
}
bool ed[1000010];
int now,huan[1000010];
ll ans;
ll pre[1000010];
ll maxl;
ll maxd;
ll len[1000010];
ll val[1000010];
int wei;
void dfs(int u,int fa)
{
for(int i=head[u];i;i=edge[i].nex)
{
int v=edge[i].to;
if(v==fa) continue;
if(huan[v]&&v!=now) continue;
len[v]=len[u]+edge[i].dis;
if(len[v]>maxl)
{
maxl=len[v];
wei=v;
}
dfs(v,u);
}
}
ll mxnum[1000010][2];
bool ko[1000010];
void dfs3(int u)
{
ko[u]=true;
for(int i=head[u];i;i=edge[i].nex)
{
int v=edge[i].to;
if(ko[v]) continue;
dfs3(v);
}
}
int main()
{
n=qread();
for(int i=1;i<=n;i++)
{
s[i]=qread();
a[i]=qread();
add(i,s[i],a[i]);
add(s[i],i,a[i]);
}
for(int i=1;i<=n;i++)
{
if(!ko[i])
{
maxd=0;
findrt(i);
int cnt=0;
ll temp=root;
while(1)
{
huan[temp]=++cnt;
temp=s[temp];
if(temp==root)break;
}
//cout<<cnt<<"++"<<endl;
temp=root;
while(1)
{
maxl=0;
len[temp]=0;
now=temp;
dfs(temp,-1);
// cout<<huan[temp]<<":"<<maxl<<endl;
val[huan[temp]]=maxl;
len[wei]=0;
maxl=0;
dfs(wei,-1);
maxd=max(maxd,maxl);
temp=s[temp];
if(temp==root) break;
}
temp=root;
pre[1]=0;
ll llen=0;
while(1)
{
pre[huan[temp]+1]=pre[huan[temp]]+a[temp];
llen+=a[temp];
temp=s[temp];
if(temp==root) {break;}
}
mxnum[0][0]=mxnum[0][1]=-123456789;
for(int i=1;i<=cnt;i++)
{
mxnum[i][0]=max(mxnum[i-1][0],val[i]-pre[i]);
mxnum[i][1]=max(mxnum[i-1][1],val[i]+pre[i]);
// cout<<val[i]<<"!!"<<pre[i]<<endl;
}
temp=maxd;
for(int i=2;i<=cnt;i++)
{
temp=max(temp,max(mxnum[i-1][0]+pre[i]+val[i],mxnum[i-1][1]+val[i]-pre[i]+llen));
//cout<<temp<<"!"<<endl;
}
// cout<<temp<<"?"<<root<<endl;
ans+=temp;
dfs3(root);
}
}
printf("%lld\n",ans);
return 0;
}