#include<bits/stdc++.h>
#define ll long long
#define reg register
#define db double
#define il inline
using namespace std;
const int N=1e6+5;
int n;
int head[N],to[N*2],nex[N*2];ll w[N*2],cnt=1;
void add(int u,int v,int ww){
cnt++;
to[cnt]=v;nex[cnt]=head[u];w[cnt]=ww;
head[u]=cnt;
}
vector<int>huan,huan_w;
int fa[N],to_fa[N];
bool vis[N],in[N];
bool flag;
void dfs2(int x,int f){
vis[x]=1;
for(int i=head[x];i;i=nex[i]){
if(!vis[to[i]])dfs2(to[i],x);
}
}
void dfs(int x,int f){
if(flag)return;
// cout<<'a'<<x<<endl;
for(int i=head[x];i;i=nex[i]){
int y=to[i];
if((f^1)==i){
// cout<<x<<' '<<f<<' '<<i<<endl;
continue;
}
// if(y==7){
// cout<<"abcd";
// }
if(fa[y]==0){
to_fa[y]=w[i];
fa[y]=x;
dfs(y,i);
}else if(flag==0){
fa[y]=x;
to_fa[y]=w[i];
int j=x;
do{
// cout<<j<<' '<<to_fa[j]<<"huan"<<endl;
if(j==0)return;
huan.push_back(j);
huan_w.push_back(to_fa[j]);
in[j]=1;
j=fa[j];
}while(j!=x);
flag=1;
}
}
}
ll d[N];
ll dp(int x,int f){
// cout<<"dp"<<x<<endl;
ll re=0;
for(int i=head[x];i;i=nex[i]){
ll y=to[i],c=w[i];
if(y==f)continue;
if(in[y])continue;
re=max(re,dp(y,x));
re=max(re,d[x]+d[y]+c);
d[x]=max(d[x],d[y]+c);
}
return re;
}
signed main(){
scanf("%d",&n);
for(int u,ww,i=1;i<=n;i++){
scanf("%d%d",&u,&ww);
add(u,i,ww);add(i,u,ww);
}
ll ans=0,maxx=0;
for(int i=1;i<=n;i++){
if(vis[i])continue;
maxx=0;
huan.clear();
huan_w.clear();
flag=0;
//cout<<i<<endl;
dfs(i,0);
dfs2(i,-1);
for(auto j:huan){
maxx=max(maxx,dp(j,0));
}
// cout<<maxx<<"max";
int tmp[2*N]={0};
ll summ[2*N]={0};
int m=huan.size();
for(int j=0;j<huan.size();j++){
tmp[j+1]=huan[j];
tmp[j+1+m]=huan[j];
summ[j+2]=huan_w[j];
summ[j+2+m]=huan_w[j];
}
for(int j=m+1;j<=m*2;j++){
tmp[j]=tmp[j-m];
}
// cout<<endl;
for(int j=1;j<=m*2;j++)summ[j]+=summ[j-1];
// cout<<endl;/
deque<int>q;
for(int j=1;j<=m*2;j++){
while(!q.empty()&&j-q.front()+1>m)q.pop_front();
if(j!=1){
int x=q.front();
maxx=max(maxx,summ[j]-summ[x]+d[tmp[x]]+d[tmp[j]]);
}
while(!q.empty()&&d[tmp[q.front()]]-summ[q.front()]<=d[tmp[j]]-summ[j])q.pop_back();
q.push_back(j);
}
// cout<<"max"<<maxx<<endl;
ans+=maxx;
}
// cout<<endl;
// for(int i=1;i<=n;i++)cout<<d[i]<<' ';
// cout<<to_fa[2]<<' '<<to_fa[7];
cout<<ans;
return 0;
}