#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,ans;
int a[200000],b[200000];//出
int s[200000];//入
priority_queue<pair<int,int>> f;
int vis[200000];
signed main(){
freopen("prob1_silver_22open.in","r",stdin);
freopen("prob1_silver_22open.out","w",stdout);
cin>>n;
for(int q=1;q<=n;q++)
{
cin>>a[q]>>b[q];
ans+=b[q];
s[a[q]]+=b[q];
}
for(int q=1;q<=n;q++) f.push({-s[q],q});
while(f.size())
{
int h=f.top().second,z=f.top().first;
f.pop();
if(vis[h]) continue;
ans+=z;
vis[h]=1;
s[a[h]]-=b[h];
f.push({-s[a[h]],a[h]});
}
cout<<ans;
return 0;
}