//love yjl forever
#include<bits/stdc++.h>
using namespace std;
#define ll long long 
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define fi first
#define se second
const int INF=0x3f3f3f3f,N=1e6+5;
int n;
int si[N],a[N];
ll dp[N];
vector<int> v[N];
int fa[N];
int b[N];
void dfs(int x)
{
	ll maxi=0;
	int tot=0;
	for(int i=0;i<v[x].size();i++)
	{
		int u=v[x][i];
		if(u==fa[x]) continue;
		dfs(u);
		si[x]+=si[u];
		dp[x]+=dp[u];
//		a[++tot]=si[u];
	}
	for(int i=0;i<v[x].size();i++)
	{
		int u=v[x][i];
		b[++tot]=si[u];
	}
	if(tot)
	{
		sort(b+1,b+tot+1);
		for(int i=1;i<=tot;i++)
		{
			dp[x]+=b[i]*(tot-i);
		}		
	}

	si[x]+=a[x];
}
int main()
{
/*	freopen("","r",stdin);
	freopen("","w",stdout);*/
	int i;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		scanf("%lld%d",&a[i],&fa[i]);
		fa[i]++;
		if(fa[i]!=0)
		{
			v[fa[i]].pb(i);
		}
	}
	ll ans=0;
	for(i=1;i<=n;i++)
	{
		if(fa[i]==0)
		{
			dfs(i);
			ans+=dp[i];
		}		
	}
	cout<<ans<<endl;
}
