#pragma comment(linker, "/STACK:204800000,204800000");
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int n,sum,l[1000000],vis[1000000],S[4000000],stage[4000000],top;
long long ans;
vector <int> g[1000000];
int DFS(int v){
	for (int i=0;i<g[v].size();i++) l[v]+=DFS(g[v][i]);
	return l[v];
}
bool cmp(int a,int b){
	return l[a]<l[b];
}
int main(){
	scanf("%d",&n);
	for (int i=0;i<n;i++){
		int b;
		scanf("%d%d",&l[i],&b);
		if (b!=-1){
			g[b].push_back(i);
			vis[i]=1;
		}
	}
	for (int i=0;i<n;i++) if (!vis[i]){
		S[0]=i;
		stage[0]=0;
		top=0;
		while (top!=-1){
			int cur=S[top];
			if (stage[top]==g[cur].size()){
				top--;
				if (top!=-1){
					l[S[top]]+=l[S[top+1]];
//printf("%d-%d\n",S[top],S[top+1]);
				}
			}
			else{
				S[top+1]=g[cur][stage[top]];
				stage[top]++;
				stage[++top]=0;
			}
		}
	}
	for (int i=0;i<n;i++) sort(g[i].begin(),g[i].end(),cmp);
	for (int i=0;i<n;i++){
		sum=0;
		for (int j=0;j<g[i].size();j++){
			ans+=sum;
			sum+=l[g[i][j]];
		}
	}
	//for (int i=0;i<n;i++) printf("%d ",l[i]);
	//printf("\n");
	printf("%lld\n",ans);
	return 0;
}