#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <map>
//#include <time.h>
#include <queue>
#include <set>
#include <string>
#include <string.h>
#include <stack>
#include <assert.h>
#include <bitset>
#define Endl endl
#define mp make_pair
#define ll long long 
#define ull unsigned long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define over(A) {cout<<A<<endl;exit(0);}
#define all(A) A.begin(),A.end()
#define ceil(a,b) ((a-1)/b+1)
#define quickcin ios_base::sync_with_stdio(false);
const int mod=1e9+7;
const int inf=1039074182;
const ll llinf=1LL*inf*inf;
using namespace std;
template <typename T1,typename T2> inline void chmin(T1 &x,T2 b) {if(b<x) x=b;}
template <typename T1,typename T2> inline void chmax(T1 &x,T2 b) {if(b>x) x=b;}
template <typename T1,typename T2> inline void chadd(T1 &x,T2 b) {x+=b;if(x>=mod) x-=mod;}
template <typename T1,typename T2> inline void chmul(T1 &x,T2 b) {x=1LL*x*b%mod;}
template <typename T1,typename T2> inline void chmod(T1 &x,T2 b) {x%=b,x+=b;if(x>=b) x-=b;}
int n;
int a[1000005];
int par[1000005];
vector <int> vec[1000005];
int sz[1000005];

inline ll dfs(int x)
{
	ll res=0;
	int sm=0;
	int mx=0;
	vector <int> v;
	v.reserve((int)vec[x].size());
	for(auto u:vec[x])
	{
		if(u==par[x]) continue;
		res+=dfs(u);
		v.push_back(sz[u]);
	}
	sort(all(v));
	for(auto value:v)
	{
		res+=sm;
		sm+=value;
	}
	return res;
}

inline int getnum()
{
	int res=0;
	char c=0;
	int neg=1;
	while(!isdigit(c) && c!='-') c=getchar();
	if(c=='-')
	{
		neg=-1;
		c=getchar();
	}
	while(isdigit(c)) res=res*10+c-'0',c=getchar();
	return res*neg;
}

vector <int> order;
vector <int> v[1000005];
ll res[1000005];

int main()
{
//	freopen("input.txt","r",stdin);
	n=getnum();
	vector <int> st;
	for(int i=0;i<n;i++)
	{
		a[i]=getnum();
		par[i]=getnum();
		if(par[i]==-1)
		{
			st.push_back(i);
		}
		else
		{
			vec[par[i]].push_back(i);
		}
	}
	queue <int> que;
	for(auto x:st)
	{
		que.push(x);
	}
	while(que.size())
	{
		int tp=que.front();
		que.pop();
		order.push_back(tp);
		for(auto u:vec[tp])
		{
			que.push(u);
		}
	}
	reverse(all(order));
	for(int i=0;i<n;i++)
	{
		sz[i]=a[i];
	}
	for(int i=0;i<n;i++)
	{
		int x=order[i];
		if(par[x]==-1) continue;
		sz[par[x]]+=sz[x];
	}
	ll ans=0;
	for(int i=0;i<n;i++)
	{
		int x=order[i];
		
		sort(all(v[x]));
		int sm=0;
		for(auto value:v[x])
		{
			res[x]+=sm;
			sm+=value;
		}
		
		if(par[x]==-1)
		{
			ans+=res[x];
			continue;
		}
		v[par[x]].push_back(sz[x]);
		res[par[x]]+=res[x];
	}	
	cout<<ans<<endl;
	return 0;
}
