#include<queue>
#include<cstdio>
#include<algorithm>

#define rep(i,n) for(int i=0;i<(n);i++)

using namespace std;

typedef long long ll;

int main(){
	int n; scanf("%d",&n);
	static vector<int> G[1000000],G_rev[1000000];
	static int cost[1000000];
	rep(u,n){
		int v; scanf("%d%d",cost+u,&v);
		if(v!=-1){
			G[v].push_back(u);
			G_rev[u].push_back(v);
		}
	}

	vector<int> topo; // topological order
	queue<int> Q;
	rep(u,n) if(G_rev[u].empty()) {
		Q.push(u);
		while(!Q.empty()){
			int v=Q.front(); Q.pop();
			topo.push_back(v);
			rep(i,G[v].size()) Q.push(G[v][i]);
		}
	}

	ll ans=0;
	for(int i=(int)topo.size()-1;i>=0;i--){
		int u=topo[i];

		vector<int> C(G[u].size()); // 頂点 u の子たちの cost
		rep(j,G[u].size()) C[j]=cost[G[u][j]];
		sort(C.begin(),C.end());

		ll sum=0;
		rep(j,C.size()){
			ans+=sum;
			sum+=C[j];
		}
		cost[u]+=sum;
	}

	printf("%lld\n",ans);

	return 0;
}