#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);
}
}
int dao[N];
int dfs(int x,int f){
if(dao[x]==1){
dao[x]=2;huan.push_back(x);
in[x]=1;
huan_w.push_back(to_fa[x]);
return 1;
}
dao[x]=1;
for(int i=head[x];i;i=nex[i]){
if(i==(f^1))continue;
to_fa[to[i]]=w[i];
if(dfs(to[i],i)){
if(dao[x]!=2){
huan.push_back(x);
huan_w.push_back(to_fa[x]);
in[x]=1;
}else{
return 0;
}
return 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;
}
int tmp[2*N]={0};
ll summ[2*N]={0};
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;
dfs(i,0);
dfs2(i,-1);
for(auto j:huan){
maxx=max(maxx,dp(j,0));
}
int m=huan.size();
for(int i=1;i<=m*2;i++)summ[i]=0;
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];
}
for(int j=1;j<=m*2;j++){
summ[j]+=summ[j-1];
}
deque<int>q;
for(int j=1;j<=m*2;j++){
while(!q.empty()&&q.front()<=j-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.back()]]-summ[q.back()]<=d[tmp[j]]-summ[j]){
q.pop_back();
}
q.push_back(j);
}
ans+=maxx;
}
cout<<ans;
return 0;
}