//2019/09/27
#include<bits/stdc++.h>
using namespace std;
template <typename T>inline void rd(T &x){x=0;char c=getchar();int f=0;while(!isdigit(c)){f|=c=='-';c=getchar();}while(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();}x=f?-x:x;}
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define dwn(i,a,b) for(int i=(a);i>=(b);--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define ee(i,u) for(int i=head[u];i;i=e[i].next)
const int N=1e5+10;
struct edge{
int v,next,w;
}e[N];
int head[N],edge_num;
inline void add(int u,int v,int w){e[++edge_num].v=v;e[edge_num].w=w;e[edge_num].next=head[u];head[u]=edge_num;}
int n,ans;
int deg[N];
queue<int>q;
inline void topo_sort(){
while(!q.empty()){
int u=q.front();q.pop();
ee(i,u){
int v=e[i].v;
if(--deg[v]==0)
q.push(v);
}
}
}
inline void get_ring(){
int res=0;
while(!q.empty()){
int u=q.front();q.pop();
ee(i,u){
int v=e[i].v,w=e[i].w;
if(!deg[v])continue;
res+=w;
deg[v]--;
q.push(v);
}
}
ans=max(ans,res);
}
int main(){
#ifdef WIN32
freopen("","r",stdin);
#endif
rd(n);
rep(i,1,n){
int v,w;rd(v),rd(w);
deg[v]++;
add(i,v,w);
}
rep(i,1,n)
if(!deg[i])
q.push(i);
topo_sort();
rep(i,1,n)
if(deg[i]){
q.push(i);
get_ring();
}
printf("%d",ans);
return 0;
}
//2019/09/27
#include<bits/stdc++.h>
using namespace std;
template <typename T>inline void rd(T &x){x=0;char c=getchar();int f=0;while(!isdigit(c)){f|=c=='-';c=getchar();}while(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();}x=f?-x:x;}
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define dwn(i,a,b) for(int i=(a);i>=(b);--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define ee(i,u) for(int i=head[u];i;i=e[i].next)
const int N=2e5+10;
struct edge{
int v,next,w;
}e[N];
int head[N],edge_num;
inline void add(int u,int v,int w){e[++edge_num].v=v;e[edge_num].w=w;e[edge_num].next=head[u];head[u]=edge_num;}
int n,ans=INT_MAX;
int deg[N];
queue<int>q;
inline void topo_sort(){
while(!q.empty()){
int u=q.front();q.pop();
ee(i,u){
int v=e[i].v;
if(--deg[v]==0)
q.push(v);
}
}
}
inline void get_ring(){
int res=0;
while(!q.empty()){
int u=q.front();q.pop();
ee(i,u){
int v=e[i].v,w=e[i].w;
if(!deg[v])continue;
res+=w;
deg[v]--;
q.push(v);
}
}
ans=min(ans,res);
}
int main(){
#ifdef WIN32
freopen("","r",stdin);
#endif
rd(n);
rep(i,1,n){
int v;rd(v);
deg[v]++;
add(i,v,1);
}
rep(i,1,n)
if(!deg[i])
q.push(i);
topo_sort();
rep(i,1,n)
if(deg[i]){
q.push(i);
get_ring();
}
printf("%d",ans);
return 0;
}