Problem:
Usoperanto
Usoperanto is an artificial spoken language designed and regulated by Usoperanto Academy.
The academy is now in study to establish Strict Usoperanto, a variation of the language intended for formal documents.
In Usoperanto, each word can modify at most one other word, and modifiers are always put before modifiees.
For example, with a noun
uso
("truth") modified by an adjective
makka
("total"), people say
makka uso
, not
uso makka
.
On the other hand, there have been no rules about the order among multiple words modifying the same word,
so in case
uso
is modified by one more adjective
beta
("obvious"),
people could say both
makka beta uso
and
beta makka uso
.
In Strict Usoperanto, the word order will be restricted according to
modification costs
.
Words in a phrase must be arranged so that the total modification cost is minimized.
Each pair of a modifier and a modifiee is assigned a cost equal to the number of letters between the two words;
the total modification cost is the sum of the costs over all modifier-modifiee pairs in the phrase.
For example, the pair of
makka
and
uso
in a phrase
makka beta uso
has the cost of 4 for
beta
(four letters).
As the pair of
beta
and
uso
has no words in between and thus the cost of zero,
makka beta uso
has the total modification cost of 4.
Similarly
beta makka uso
has the total modification cost of 5.
Applying the "minimum total modification cost" rule,
makka beta uso
is preferred to
beta makka uso
in Strict Usoperanto.
Your mission in this problem is to write a program that, given a set of words in a phrase, finds the correct word order in Strict Usoperanto and reports the total modification cost.
Input
The format of the input is as follows.
N
M
0
L
0
...
M
N-1
L
N-1
The first line contains an integer
N
(
1 ≤ N ≤ 10
6
).
N
is the number of words in a phrase.
Each of the following
N
lines contains two integers
M
i
(
1 ≤ M
i
≤ 10
) and
L
i
(
-1 ≤ L
i
≤ N - 1
,
L
i
≠ i
)
describing the
i
-th word (
0 ≤ i ≤ N-1
).
M
i
is the number of the letters in the word.
L
i
specifies the modification:
L
i
= -1
indicates it does not modify any word;
otherwise it modifies the
L
i
-th word.
Note the first sample input below can be interpreted as the
uso
-
beta
-
makka
case.
Output
Print the total modification cost.
Sample Input 1
3
3 -1
4 0
5 0
Output for the Sample Input 1
4
Sample Input 2
3
10 -1
10 0
10 1
Output for the Sample Input 2
0
Sample Input 3
4
1 -1
1 0
1 1
1 0
Output for the Sample Input 3
1

Submitted solutions:

code_snippet: /*
 * main.cpp
 *
 *  Created on: 2014年7月8日
 *      Author: whd
 */

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>

#define mp make_pair
#define pb push_back

using namespace std;
typedef long long big;
//
//const int dx[] = { 0, 0, 1, -1 };
//const int dy[] = { 1, -1, 0, 0 };
//
//int w, h;
//char map[1 << 10][50][50];
//int id[50][50];
//int s;
//char swi[10][50][50];
//int sx, sy, tx, ty;
//bool vis[1 << 10];
//struct state {
//	int st, f, x, y;
//	state() {
//	}
//	state(int st, int f, int x, int y) :
//			st(st), f(f), x(x), y(y) {
//	}
//} q[(1 << 10) * 2 * 50 * 50];
//int qh, qt;
//int d[1 << 10][2][50][50];
//int ans;
//
//int main() {
//	scanf("%d%d", &w, &h);
//	memset(id, -1, sizeof id);
//	for (int i = 0; i < h; i++) {
//		for (int j = 0; j < w; j++) {
//			scanf(" %c", &map[0][i][j]);
//			if (map[0][i][j] == '%') {
//				sx = i, sy = j;
//				map[0][i][j] = '_';
//			}
//			if (map[0][i][j] == '&') {
//				tx = i, ty = j;
//				map[0][i][j] = '_';
//			}
//			if ('a' <= map[0][i][j] && map[0][i][j] <= 'z') {
//				id[i][j] = map[0][i][j] - 'a';
//				map[0][i][j] = '_';
//			}
//			if ('A' <= map[0][i][j] && map[0][i][j] <= 'Z') {
//				id[i][j] = map[0][i][j] - 'A';
//				map[0][i][j] = '^';
//			}
//		}
//	}
//	scanf("%d", &s);
//	for (int k = 0; k < s; k++) {
//		for (int i = 0; i < h; i++) {
//			for (int j = 0; j < w; j++) {
//				scanf(" %c", &swi[k][i][j]);
//			}
//		}
//	}
//	vis[0] = true;
//	memset(d, -1, sizeof d);
//	ans = -1;
//	q[qh] = state(0, 0, sx, sy);
//	d[0][0][sx][sy] = 0;
//	while (qh <= qt) {
//		state u = q[qh++], v;
//		if (u.f == 0 && u.x == tx && u.y == ty) {
//			ans = d[u.st][u.f][u.x][u.y];
//			break;
//		}
////		cout << u.st << " " << u.f << " " << u.x << " " << u.y << " : "
////				<< d[u.st][u.f][u.x][u.y] << endl;
////		for (int i = 0; i < h; i++) {
////			for (int j = 0; j < w; j++) {
////				cout << map[u.st][i][j];
////			}
////			cout << endl;
////		}
//		if (map[u.st][u.x][u.y] == '|') {
//			v.st = u.st, v.f = u.f ^ 1, v.x = u.x, v.y = u.y;
//			if (d[v.st][v.f][v.x][v.y] == -1) {
//				d[v.st][v.f][v.x][v.y] = d[u.st][u.f][u.x][u.y] + 1;
//				q[++qt] = v;
//			}
//		}
//		if ((map[u.st][u.x][u.y] == '|' && u.f == 0)
//				|| map[u.st][u.x][u.y] == '_') {
//			for (int dir = 0; dir < 4; dir++) {
//				v.st = u.st, v.f = u.f, v.x = u.x + dx[dir], v.y = u.y + dy[dir];
//				if ((map[v.st][v.x][v.y] == '|' && v.f == 0)
//						|| map[v.st][v.x][v.y] == '_') {
//					if (d[v.st][v.f][v.x][v.y] == -1) {
//						d[v.st][v.f][v.x][v.y] = d[u.st][u.f][u.x][u.y] + 1;
//						q[++qt] = v;
//					}
//				}
//			}
//		}
//		if ((map[u.st][u.x][u.y] == '|' && u.f == 1)
//				|| map[u.st][u.x][u.y] == '^') {
//			for (int dir = 0; dir < 4; dir++) {
//				v.st = u.st, v.f = u.f, v.x = u.x + dx[dir], v.y = u.y + dy[dir];
//				if ((map[v.st][v.x][v.y] == '|' && v.f == 1)
//						|| map[v.st][v.x][v.y] == '^') {
//					if (d[v.st][v.f][v.x][v.y] == -1) {
//						d[v.st][v.f][v.x][v.y] = d[u.st][u.f][u.x][u.y] + 1;
//						q[++qt] = v;
//					}
//				}
//			}
//		}
//		if (id[u.x][u.y] != -1) {
//			v.st = u.st ^ (1 << id[u.x][u.y]), v.f = u.f
//					^ (swi[id[u.x][u.y]][u.x][u.y] == '*'), v.x = u.x, v.y = u.y;
//			if (d[v.st][v.f][v.x][v.y] == -1) {
//				d[v.st][v.f][v.x][v.y] = d[u.st][u.f][u.x][u.y] + 1;
//				q[++qt] = v;
//			}
//			if (!vis[v.st]) {
//				for (int i = 0; i < h; i++) {
//					for (int j = 0; j < w; j++) {
//						if (swi[id[u.x][u.y]][i][j] == '*') {
//							map[v.st][i][j] = '_' + '^' - map[u.st][i][j];
//						} else {
//							map[v.st][i][j] = map[u.st][i][j];
//						}
//					}
//				}
//			}
//		}
//	}
//	printf("%d\n", ans);
//}

const int N = 1002000;
int n;
int fa[N], ind[N];
big sum[N];
int q[N];
int lst[N], top = 0;
int head[N], nxt[N], v[N], t = 1;
inline void add(int x, int y) {
	nxt[++t] = head[x];
	v[t] = y;
	head[x] = t;
}
int main() {
	int h, tail, s, i, x, y, j;
	scanf("%d", &n);
	for (i = 0; i < n; i++) {
		scanf("%d%d", &x, &y);
		fa[i] = y;
		if (y >= 0) {
			ind[y]++;
			add(y, i);
		}
		sum[i] = x;
	}
	h = 1;
	tail = 0;
	for (i = 0; i < n; i++)
		if (!ind[i]) {
			q[++tail] = i;
		}
	big ans = 0, tmp = 0;
	while (h <= tail) {
		s = q[h++];
		top = 0;
		for (i = head[s]; i; i = nxt[i]) {
			lst[++top] = sum[v[i]];
		}
		sort(lst + 1, lst + 1 + top);

		tmp = 0;
		for (i = 1; i < top; i++) {
			tmp += lst[i];
			ans += tmp;
		}
		if (fa[s] >= 0) {
			--ind[fa[s]];
			sum[fa[s]] += sum[s];
			if (!ind[fa[s]])
				q[++tail] = fa[s];
		}
	}
	cout << ans << endl;
}

//int n, m;
//int t[12], a[20][20];
//vector<pair<int, int> > lst;
//int ans;
//bool vis[20][20];
//bool g[20][4];
//void init() {
//	int i, j;
//	memset(g, false, sizeof(g));
//	g[1][0] = g[1][2] = true;
//	g[2][1] = g[2][3] = true;
//	g[3][0] = g[3][1] = true;
//	g[4][1] = g[4][2] = true;
//	g[5][2] = g[5][3] = true;
//	g[6][3] = g[6][0] = true;
//	g[7][0] = g[7][1] = g[7][2] = true;
//	g[8][1] = g[8][2] = g[8][3] = true;
//	g[9][0] = g[9][2] = g[9][3] = true;
//	g[10][0] = g[10][1] = g[10][3] = true;
//	g[11][0] = g[11][1] = g[11][2] = g[11][3] = true;
//}
//void ff(int x, int y) {
//	vis[x][y] = true;
//	if (!vis[x + 1][y] && g[a[x][y]][2] && g[a[x + 1][y]][0])
//		ff(x + 1, y);
//	if (!vis[x - 1][y] && g[a[x][y]][0] && g[a[x - 1][y]][2])
//		ff(x - 1, y);
//	if (!vis[x][y + 1] && g[a[x][y]][1] && g[a[x][y + 1]][3])
//		ff(x, y + 1);
//	if (!vis[x][y - 1] && g[a[x][y]][3] && g[a[x][y - 1]][1])
//		ff(x, y - 1);
//}
//bool check() {
//	int i, j;
//	for (i = 1; i <= n; i++)
//		for (j = 1; j <= m; j++)
//			vis[i][j] = false;
//	ff(1, 1);
//	return vis[n][m];
//}
//void dfs(int dep) {
//	if (dep == lst.size()) {
//		ans += check();
//		return ;
//	}
//	int i, x = lst[dep].first, y = lst[dep].second;
//	for (i = 0; i < 12; i++) {
//		if (t[i]) {
//			t[i]--;
//			a[x][y] = i;
//			if (g[a[1][1]][1] || g[a[1][1]][2])
//				dfs(dep + 1);
//			t[i]++;
//		}
//	}
//}
//int main() {
//	int i, j;
//	init();
//	scanf("%d%d", &n, &m);
//	for (i = 0; i < 12; i++)
//		scanf("%d", &t[i]);
//	for (i = 1; i <= n; i++)
//		for (j = 1; j <= m; j++)
//			lst.pb(mp(i, j));
//	for (i = 0; i < n + 1; i++)
//		for (j = 0; j < m + 1; j++)
//			vis[i][j] = true;
//	dfs(0);
//	printf("%d\n", ans);
//}
accuracy: 1
time_ms: 160
memory_kb: 38688
final_rank: 1

code_snippet: #include <iostream>	
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>	
#pragma comment(linker,"/STACK:10240000000,10240000000")
using namespace std;

const int maxn=1e6+5;
int a[maxn][2],b[maxn],bl;
vector<int> e[maxn];
vector<int> te[maxn];
long long tot=0;
long long dfs(int node)
{
	if (e[node].size()==0)
		return a[node][0];
	//printf("good");
	long long temp;
	long long sum=0,sum1=0;
	long long mx=0;
	int l=e[node].size();
	for (int i=0;i<l;i++)
	{
		temp=dfs(e[node][i]);
		te[node][i]=temp;
		sum+=temp;
		if (temp>mx)
			mx=temp;
	}
	sort(te[node].begin(),te[node].end());
	for (int i=0;i<l-1;i++)
	{
		sum1+=te[node][i]*(l-i-1);
	}
	tot+=sum1;
	te[node].resize(0);
	return sum+a[node][0];
}

int main()
{
	int n;
	scanf("%d",&n);
	bl=0;
	for (int i=0;i<n;i++)
	{
		scanf("%d%d",&a[i][0],&a[i][1]);
		if (a[i][1]!=-1)
			e[a[i][1]].push_back(i);
		else 
			b[bl++]=i;
	}
	for (int i=0;i<n;i++)
		te[i].resize(e[i].size());
	for (int j=0;j<bl;j++)
	{
		dfs(b[j]);
	}
	printf("%lld\n",tot);
	return 0;
}
accuracy: 1
time_ms: 430
memory_kb: 200612
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MAXN = 1000000 + 3;

vector<vector<int> > E;
vector<int> a;
queue<int> q;
int v[MAXN], f[MAXN], ind[MAXN];
int n;

int main()
{
    scanf("%d", &n);
    E.clear();
    E.resize(n+1);
    for (int i = 0; i < n; ++i) {
        int x, y;
        scanf("%d%d", &x, &y);
        v[i] = x;
        if (y != -1) {
            ind[y] ++;
            f[i] = y;
            E[y].push_back(i);
        }
    }
    for (int i = 0; i < n; ++i) {
        if (ind[i] == 0) {
            q.push(i);
        }
    }
    LL ans = 0;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        a.clear();
        for (int i = 0; i < E[x].size(); ++i) {
            int y = E[x][i];
            a.push_back(v[y]);
        }
        sort(a.begin(), a.end());
        int cur = 0;
        for (int i = 0; i < a.size(); ++i) {
            ans += cur;
            cur += a[i];
        }
        v[x] += cur;
        if (--ind[f[x]] == 0) q.push(f[x]);
    }
    cout << ans << endl;
    return 0;
}
accuracy: 0.9444444444444444
time_ms: 300
memory_kb: 69396
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MAXN = 1000000 + 3;

vector<vector<int> > E;
vector<int> a;
queue<int> q;
int v[MAXN], f[MAXN], ind[MAXN];
int n;

int main()
{
    while (scanf("%d", &n) != EOF) {
        E.clear();
        E.resize(n+1);
        memset(ind, 0, sizeof ind);
        for (int i = 0; i < n; ++i) {
            int x, y;
            scanf("%d%d", &x, &y);
            v[i] = x;
            if (y != -1) {
                ind[y] ++;
                f[i] = y;
                E[y].push_back(i);
            }
        }
        while (!q.empty()) q.pop();
        for (int i = 0; i < n; ++i) {
            if (ind[i] == 0) {
                q.push(i);
            }
        }
        LL ans = 0;
        while (!q.empty()) {
            int x = q.front();
            q.pop();
            a.clear();
            for (int i = 0; i < E[x].size(); ++i) {
                int y = E[x][i];
                a.push_back(v[y]);
            }
            sort(a.begin(), a.end());
            int cur = 0;
            for (int i = 0; i < a.size(); ++i) {
                ans += cur;
                cur += a[i];
            }
            v[x] += cur;
            if (--ind[f[x]] == 0) q.push(f[x]);
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 0.9444444444444444
time_ms: 290
memory_kb: 69344
final_rank: 17

code_snippet: #pragma comment(linker, "/STACK:204800000,204800000");
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int n,sum,l[1000000],vis[1000000];
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]) DFS(i);
	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;
}
accuracy: 1
time_ms: 360
memory_kb: 96544
final_rank: 4

code_snippet: #include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mp make_pair
#define pb push_back
#define fst first
#define snd second
typedef long long ll;
typedef pair<int,int> pii;

const int maxn=1000005;
int n;
int a[maxn],sz[maxn];
ll dp[maxn];
vector<int>edge[maxn],rt;
bool cmp(int a,int b){return sz[a]<sz[b];}

void dfs(int x){
	rep(i,int(edge[x].size()))
		dfs(edge[x][i]);
	sort(edge[x].begin(),edge[x].end(),cmp);
	rep(i,int(edge[x].size())){
		int y=edge[x][i];
		dp[x]+=dp[y]+sz[x];
		sz[x]+=sz[y];
	}
	sz[x]+=a[x];
}

int main(){
	scanf("%d",&n);
	rep(i,n){
		scanf("%d",&a[i]);
		int p;scanf("%d",&p);
		if(p>=0)edge[p].pb(i);
		else rt.pb(i);
	}
	ll ans=0;
	rep(i,int(rt.size())){
		dfs(rt[i]);
		ans+=dp[rt[i]];
	}
	printf("%lld\n",ans);
	return 0;
}
accuracy: 1
time_ms: 430
memory_kb: 151896
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mp make_pair
#define pb push_back
#define fst first
#define snd second
typedef long long ll;
typedef pair<int,int> pii;

const int maxn=1000005;
int n;
int a[maxn],sz[maxn];
ll dp[maxn];
vector<int>edge[maxn],rt;
bool cmp(int a,int b){return sz[a]<sz[b];}

void dfs(int x){
	rep(i,int(edge[x].size()))
		dfs(edge[x][i]);
	if(!edge[x].empty())
		sort(edge[x].begin(),edge[x].end(),cmp);
	rep(i,int(edge[x].size())){
		int y=edge[x][i];
		dp[x]+=dp[y]+sz[x];
		sz[x]+=sz[y];
	}
	sz[x]+=a[x];
}

int main(){
	scanf("%d",&n);
	rep(i,n){
		scanf("%d",&a[i]);
		int p;scanf("%d",&p);
		if(p>=0)edge[p].pb(i);
		else rt.pb(i);
	}
	ll ans=0;
	rep(i,int(rt.size())){
		dfs(rt[i]);
		ans+=dp[rt[i]];
	}
	printf("%lld\n",ans);
	return 0;
}
accuracy: 1
time_ms: 420
memory_kb: 151896
final_rank: 5

code_snippet: /*
Though leaves are many , the root is one.
Through all the lying days of my youth
I swayed my leaves and flowers in the sun.
Now I may wither into the truth.
	  	  	- William Butler Yeats
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
//#pragma GCC target("avx,tune=native")
#include<bits/stdc++.h>
#define int long long
#pragma comment("-Wl,--stack=1024000000")
//#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
namespace fastio{
    char in[100000];
    int itr=0,llen=0;
    char get(){
        if(itr==llen)llen=fread(in,1,100000,stdin),itr=0;
        if(llen==0)return EOF;
        return in[itr++];
    }
    char out[100000];
    int itr2=0;
    void put(char c){
        out[itr2++]=c;
        if(itr2==100000){
            fwrite(out,1,100000,stdout);
            itr2=0;
        }
    }
    int clear(){
        fwrite(out,1,itr2,stdout);
        itr2=0;
        return 0;
    }
    int getint(){
        int ret=0;char ch=get();
        if(ch=='-')return -getint();
        while (ch<'0'||ch>'9'){
            ch=get();if(ch=='-')return -getint();
        }
        while ('0'<=ch&&ch<='9'){
            ret=ret*10-48+ch;
            ch=get();
        }
        return ret;
    }
    string getstr(){
        string ret="";
        char ch=get();
        while(ch==' '||ch=='\n')ch=get();
        while(ch!=' '&&ch!='\n')ret.push_back(ch),ch=get();
        return ret;
    }
    void putstr(string s){
        for(int i=0;i<s.size();i++)put(s[i]);
    }
    void putint(int x){
        if(x<0){
            put('-');
            putint(-x);
            return;
        }
        if(x==0){
            put('0');put(' ');
            return;
        }
        char c[40];int pos=0;
        while(x){
            c[pos++]='0'+x%10;
            x/=10;
        }
        for(int i=pos-1;i>=0;i--)put(c[i]);
        put(' ');
    }
    void putln(int x){
        if(x<0){
            put('-');
            putln(-x);
            return;
        }
        if(x==0){
            put('0');put('\n');
            return;
        }
        char c[40];int pos=0;
        while(x){
            c[pos++]='0'+x%10;
            x/=10;
        }
        for(int i=pos-1;i>=0;i--)put(c[i]);
        put('\n');
    }
}
using namespace fastio;
//using namespace __gnu_pbds;
const int inf=0x3f3f3f3f;
const double eps=1e-6;
const int mod=1000000007;
typedef long long ll;
#ifndef LOCAL
#define cerr if(0)cout
#define eprintf(...) 0
#else
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#endif
inline string getstr(string &s,int l,int r){string ret="";for(int i=l;i<=r;i++)ret.push_back(s[i]);return ret;}
int modpow(int x,int y,int md=mod){int ret=1;do{if(y&1)ret=(ll)ret*x%md;x=(ll)x*x%md;}while(y>>=1);return ret;}
inline int Rand(){return rand()*32768+rand();}
int n;
int len[1000005],p[1000005];
int dp[1000005],sz[1000005],sum[1000005],ans[1000005];
vector<int>roots,g[1000005];
//first--->cost
//second-->sz
bool cmp(int x,int y){
	return sum[x]<sum[y];
}
void dfs(int x){
	sz[x]=1;
	vector<int>ord;
	for(auto to:g[x]){
		dfs(to);sz[x]+=sz[to]; 
		ord.push_back(to);
		ans[x]+=ans[to];
	}
	sort(ord.begin(),ord.end(),cmp);
	for(auto to:ord){
		dp[x]+=sum[x];
		sum[x]+=sum[to];
	}
	ans[x]+=dp[x];
	sum[x]+=len[x];
}
signed main(){
	n=getint();
	for(int i=0;i<n;i++){
		len[i]=getint();p[i]=getint();
		if(p[i]!=-1)g[p[i]].push_back(i);
		else roots.push_back(i);
	}
	int fans=0,tot=0;
	for(auto x:roots){
		dfs(x);
		fans+=ans[x];
		tot+=sz[x];
	}
	assert(tot==n);
	cout<<fans<<endl;
	return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 198596
final_rank: 10

code_snippet: /*
Though leaves are many , the root is one.
Through all the lying days of my youth
I swayed my leaves and flowers in the sun.
Now I may wither into the truth.
	  	  	- William Butler Yeats
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
//#pragma GCC target("avx,tune=native")
#include<bits/stdc++.h>
#define int long long
#pragma comment("-Wl,--stack=1024000000")
//#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
namespace fastio{
    char in[100000];
    int itr=0,llen=0;
    char get(){
        if(itr==llen)llen=fread(in,1,100000,stdin),itr=0;
        if(llen==0)return EOF;
        return in[itr++];
    }
    char out[100000];
    int itr2=0;
    void put(char c){
        out[itr2++]=c;
        if(itr2==100000){
            fwrite(out,1,100000,stdout);
            itr2=0;
        }
    }
    int clear(){
        fwrite(out,1,itr2,stdout);
        itr2=0;
        return 0;
    }
    int getint(){
        int ret=0;char ch=get();
        if(ch=='-')return -getint();
        while (ch<'0'||ch>'9'){
            ch=get();if(ch=='-')return -getint();
        }
        while ('0'<=ch&&ch<='9'){
            ret=ret*10-48+ch;
            ch=get();
        }
        return ret;
    }
    string getstr(){
        string ret="";
        char ch=get();
        while(ch==' '||ch=='\n')ch=get();
        while(ch!=' '&&ch!='\n')ret.push_back(ch),ch=get();
        return ret;
    }
    void putstr(string s){
        for(int i=0;i<s.size();i++)put(s[i]);
    }
    void putint(int x){
        if(x<0){
            put('-');
            putint(-x);
            return;
        }
        if(x==0){
            put('0');put(' ');
            return;
        }
        char c[40];int pos=0;
        while(x){
            c[pos++]='0'+x%10;
            x/=10;
        }
        for(int i=pos-1;i>=0;i--)put(c[i]);
        put(' ');
    }
    void putln(int x){
        if(x<0){
            put('-');
            putln(-x);
            return;
        }
        if(x==0){
            put('0');put('\n');
            return;
        }
        char c[40];int pos=0;
        while(x){
            c[pos++]='0'+x%10;
            x/=10;
        }
        for(int i=pos-1;i>=0;i--)put(c[i]);
        put('\n');
    }
}
using namespace fastio;
//using namespace __gnu_pbds;
const int inf=0x3f3f3f3f;
const double eps=1e-6;
const int mod=1000000007;
typedef long long ll;
#ifndef LOCAL
#define cerr if(0)cout
#define eprintf(...) 0
#else
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#endif
inline string getstr(string &s,int l,int r){string ret="";for(int i=l;i<=r;i++)ret.push_back(s[i]);return ret;}
int modpow(int x,int y,int md=mod){int ret=1;do{if(y&1)ret=(ll)ret*x%md;x=(ll)x*x%md;}while(y>>=1);return ret;}
inline int Rand(){return rand()*32768+rand();}
int n;
int len[1000005],p[1000005];
int dp[1000005],sz[1000005],sum[1000005],ans[1000005];
vector<int>roots,g[1000005];
//first--->cost
//second-->sz
bool cmp(int x,int y){
	return sum[x]<sum[y];
}
void dfs(int x){
	sz[x]=1;
	vector<int>ord;
	for(auto to:g[x]){
		dfs(to);sz[x]+=sz[to]; 
		ord.push_back(to);
		ans[x]+=ans[to];
	}
	sort(ord.begin(),ord.end(),cmp);
	for(auto to:ord){
		dp[x]+=sum[x];
		sum[x]+=sum[to];
	}
	ans[x]+=dp[x];
	sum[x]+=len[x];
}
signed main(){
	n=getint();
	for(int i=0;i<n;i++){
		len[i]=getint();p[i]=getint();
		if(p[i]!=-1)g[p[i]].push_back(i);
		else roots.push_back(i);
	}
	int fans=0,tot=0;
	for(auto x:roots){
		dfs(x);
		fans+=ans[x];
		tot+=sz[x];
	}
//	assert(tot==n);
	cout<<fans<<endl;
	return 0;
}
accuracy: 1
time_ms: 380
memory_kb: 198788
final_rank: 9

code_snippet: #include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring> 
#include<cassert>
#include<cmath>
#include<sstream>
#include<fstream>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<bitset>
using namespace std;
int len[1000005];
vector<int> nei[1000005];
long long num[1000005],dp[1000005];
bool root[1000005];
void dfs(int v,int pa){
	vector<long long> sonnum;
	num[v]=len[v];
	for(int i=0;i<nei[v].size();i++){
		int u=nei[v][i];
		if(u==v) continue;
		dfs(u,v);
		sonnum.push_back(num[u]);
		dp[v]+=dp[u];
		num[v]+=num[u];
	}
	sort(sonnum.begin(),sonnum.end());
	long long pre=0;
	for(int i=0;i<sonnum.size();i++){
		dp[v]+=pre;
		pre+=sonnum[i];
	}
}
int main(){
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		int x,y;
		scanf("%d %d",&x,&y);
		len[i]=x;
		if(y!=-1) nei[y].push_back(i);
		else root[i]=1;
	}
	long long res=0;
	for(int i=0;i<n;i++){
		if(root[i]){
			dfs(i,-1);
			res+=dp[i];
		}
	}
	cout<<res<<endl;
}
accuracy: 1
time_ms: 440
memory_kb: 155856
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define ll long long
#define mp make_pair
#define pb push_back

#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define rep(i, n) for (int i = 0; i < (int)(n); ++ i)

const int maxn = 1e6 + 5;

int n, r;
int v[maxn];
vector <int> g[maxn];
int pls[maxn];
int sm[maxn];

bool comp(int a, int b) {
	return sm[a] > sm[b];
}

void dfs(int u) {
	if (u < n) sm[u] = v[u];
	rep(i, g[u].size()) dfs(g[u][i]), sm[u] += sm[g[u][i]];
	sort(g[u].begin(), g[u].end(), comp);
}

vector <int> s;
void getans(int u) {
	rep(i, g[u].size()) getans(g[u][i]);
	if (u < n) s.pb(u);
}

int main() {
	r = -1;
	scanf("%d", &n);
	rep(i, n) {
		int fa;
		scanf("%d %d", &v[i], &fa);
		if (fa == -1) g[n].pb(i);
		else g[fa].pb(i);
	}
	dfs(n);
	getans(n);
	rep(i, s.size()) pls[s[i]] = i;
	vector <int> sm(s.size());
	rep(i, s.size()) sm[i] = (i ? sm[i - 1] : 0) + v[s[i]];
	ll ans = 0;
	rep(i, n) {
		rep(j, g[i].size()) {
			int to = g[i][j];
			ans += sm[pls[i] - 1] - sm[pls[to]];
		}
	}
	printf("%lld\n", ans);
	return 0;
}
accuracy: 1
time_ms: 550
memory_kb: 139680
final_rank: 13

code_snippet: /*
Though leaves are many , the root is one.
Through all the lying days of my youth
I swayed my leaves and flowers in the sun.
Now I may wither into the truth.
	  	  	- William Butler Yeats
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
//#pragma GCC target("avx,tune=native")
#include<bits/stdc++.h>
#define int long long
#pragma comment("-Wl,--stack=1024000000")
//#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
namespace fastio{
    char in[100000];
    int itr=0,llen=0;
    char get(){
        if(itr==llen)llen=fread(in,1,100000,stdin),itr=0;
        if(llen==0)return EOF;
        return in[itr++];
    }
    char out[100000];
    int itr2=0;
    void put(char c){
        out[itr2++]=c;
        if(itr2==100000){
            fwrite(out,1,100000,stdout);
            itr2=0;
        }
    }
    int clear(){
        fwrite(out,1,itr2,stdout);
        itr2=0;
        return 0;
    }
    int getint(){
        int ret=0;char ch=get();
        if(ch=='-')return -getint();
        while (ch<'0'||ch>'9'){
            ch=get();if(ch=='-')return -getint();
        }
        while ('0'<=ch&&ch<='9'){
            ret=ret*10-48+ch;
            ch=get();
        }
        return ret;
    }
    string getstr(){
        string ret="";
        char ch=get();
        while(ch==' '||ch=='\n')ch=get();
        while(ch!=' '&&ch!='\n')ret.push_back(ch),ch=get();
        return ret;
    }
    void putstr(string s){
        for(int i=0;i<s.size();i++)put(s[i]);
    }
    void putint(int x){
        if(x<0){
            put('-');
            putint(-x);
            return;
        }
        if(x==0){
            put('0');put(' ');
            return;
        }
        char c[40];int pos=0;
        while(x){
            c[pos++]='0'+x%10;
            x/=10;
        }
        for(int i=pos-1;i>=0;i--)put(c[i]);
        put(' ');
    }
    void putln(int x){
        if(x<0){
            put('-');
            putln(-x);
            return;
        }
        if(x==0){
            put('0');put('\n');
            return;
        }
        char c[40];int pos=0;
        while(x){
            c[pos++]='0'+x%10;
            x/=10;
        }
        for(int i=pos-1;i>=0;i--)put(c[i]);
        put('\n');
    }
}
using namespace fastio;
//using namespace __gnu_pbds;
const int inf=0x3f3f3f3f;
const double eps=1e-6;
const int mod=1000000007;
typedef long long ll;
#ifndef LOCAL
#define cerr if(0)cout
#define eprintf(...) 0
#else
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#endif
inline string getstr(string &s,int l,int r){string ret="";for(int i=l;i<=r;i++)ret.push_back(s[i]);return ret;}
int modpow(int x,int y,int md=mod){int ret=1;do{if(y&1)ret=(ll)ret*x%md;x=(ll)x*x%md;}while(y>>=1);return ret;}
inline int Rand(){return rand()*32768+rand();}
int n;
int len[1000005],p[1000005];
int dp[1000005],sz[1000005],sum[1000005],ans[1000005];
vector<int>roots,g[1000005];
bool cmp(int x,int y){
	return sum[x]<sum[y];
}
void dfs(int x){
	sz[x]=1;
	vector<int>ord;
	for(auto to:g[x]){
		dfs(to);
		sz[x]+=sz[to];
		ans[x]+=ans[to];
		ord.push_back(sum[to]);
	}
	sort(ord.begin(),ord.end());
	for(auto to:ord){
		dp[x]+=sum[x];
		sum[x]+=to;
	}
	ans[x]+=dp[x];
	sum[x]+=len[x];
}
signed main(){
	scanf("%lld",&n);
	for(int i=0;i<n;i++){
		scanf("%lld%lld",&len[i],&p[i]);
		if(p[i]!=-1)g[p[i]].push_back(i);
		else roots.push_back(i);
	}
	int fans=0,tot=0;
	for(auto x:roots){
		dfs(x);
		fans+=ans[x];
		tot+=sz[x];
	}
//	assert(tot==n);
	cout<<fans<<endl;
	return 0;
}
accuracy: 1
time_ms: 450
memory_kb: 182928
final_rank: 11

code_snippet: /*
Though leaves are many , the root is one.
Through all the lying days of my youth
I swayed my leaves and flowers in the sun.
Now I may wither into the truth.
	  	  	- William Butler Yeats
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
//#pragma GCC target("avx,tune=native")
#include<bits/stdc++.h>
#define int long long
//#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
//using namespace __gnu_pbds;
const int inf=0x3f3f3f3f;
const double eps=1e-6;
const int mod=1000000007;
typedef long long ll;
#ifndef LOCAL
#define cerr if(0)cout
#define eprintf(...) 0
#else
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#endif
inline string getstr(string &s,int l,int r){string ret="";for(int i=l;i<=r;i++)ret.push_back(s[i]);return ret;}
int modpow(int x,int y,int md=mod){int ret=1;do{if(y&1)ret=(ll)ret*x%md;x=(ll)x*x%md;}while(y>>=1);return ret;}
inline int Rand(){return rand()*32768+rand();}
int n;
int len[1000005],p[1000005];
int dp[1000005],sz[1000005],sum[1000005],ans[1000005];
vector<int>roots,g[1000005];
bool cmp(int x,int y){
	return sum[x]<sum[y];
}
void dfs(int x){
	sz[x]=1;
	vector<int>ord;
	for(auto to:g[x]){
		dfs(to);
		sz[x]+=sz[to];
		ans[x]+=ans[to];
		ord.push_back(sum[to]);
	}
	sort(ord.begin(),ord.end());
	for(auto to:ord){
		dp[x]+=sum[x];
		sum[x]+=to;
	}
	ans[x]+=dp[x];
	sum[x]+=len[x];
}
signed main(){
	scanf("%lld",&n);
	for(int i=0;i<n;i++){
		scanf("%lld%lld",&len[i],&p[i]);
		if(p[i]!=-1)g[p[i]].push_back(i);
		else roots.push_back(i);
	}
	int fans=0,tot=0;
	for(auto x:roots){
		dfs(x);
		fans+=ans[x];
		tot+=sz[x];
	}
//	assert(tot==n);
	cout<<fans<<endl;
	return 0;
}
accuracy: 1
time_ms: 450
memory_kb: 183116
final_rank: 12

code_snippet: /*
Though leaves are many , the root is one.
Through all the lying days of my youth
I swayed my leaves and flowers in the sun.
Now I may wither into the truth.
	  	  	- William Butler Yeats
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
//#pragma GCC target("avx,tune=native")
#include<bits/stdc++.h>
#define int long long
//#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
//using namespace __gnu_pbds;
const int inf=0x3f3f3f3f;
const double eps=1e-6;
const int mod=1000000007;
typedef long long ll;
#ifndef LOCAL
#define cerr if(0)cout
#define eprintf(...) 0
#else
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#endif
inline string getstr(string &s,int l,int r){string ret="";for(int i=l;i<=r;i++)ret.push_back(s[i]);return ret;}
int modpow(int x,int y,int md=mod){int ret=1;do{if(y&1)ret=(ll)ret*x%md;x=(ll)x*x%md;}while(y>>=1);return ret;}
inline int Rand(){return rand()*32768+rand();}
int n;
int len[1000005],p[1000005];
int dp[1000005],sz[1000005],sum[1000005],ans[1000005];
vector<int>roots,g[1000005];
bool cmp(int x,int y){
	return sum[x]<sum[y];
}
void dfs(int x){
	sz[x]=1;
	vector<int>ord;
	for(auto to:g[x]){
		dfs(to);
		sz[x]+=sz[to];
		ans[x]+=ans[to];
	}
	for(auto to:g[x]){
		ord.push_back(sum[to]);
	}
	sort(ord.begin(),ord.end());
	for(auto to:ord){
		dp[x]+=sum[x];
		sum[x]+=to;
	}
	ans[x]+=dp[x];
	sum[x]+=len[x];
}
signed main(){
	scanf("%lld",&n);
	for(int i=0;i<n;i++){
		scanf("%lld%lld",&len[i],&p[i]);
		if(p[i]!=-1)g[p[i]].push_back(i);
		else roots.push_back(i);
	}
	int fans=0,tot=0;
	for(auto x:roots){
		dfs(x);
		fans+=ans[x];
		tot+=sz[x];
	}
//	assert(tot==n);
	cout<<fans<<endl;
	return 0;
}
accuracy: 1
time_ms: 520
memory_kb: 198716
final_rank: 16

code_snippet: #include<bits/stdc++.h>

using namespace std;

#define FOR(i, x, y) for(int i = (x); i < (y); ++i)
#define REP(i, x, y) for(int i = (x); i <= (y); ++i)
#define PB push_back
#define MP make_pair
#define PH push
#define fst first
#define snd second
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair<int, int> pii;

const int maxn = 1e6 + 5;

int n, f;
int a[maxn], p[maxn], vis[maxn];
ll sz[maxn];
ll dp[maxn];
ll ans;
vector<int> g[maxn];

inline bool cmp(int &u, int &v){
	return sz[u] < sz[v];
}

inline void dfs(int u, int p){
	vector<int> son;
	son.clear();
	vis[u] = true;
	FOR(i, 0, g[u].size()){
		int v = g[u][i];
		if(v == p)
			continue;
		son.PB(v);
		dfs(v, u);
		dp[u] += dp[v]; 
	}
	sort(son.begin(), son.end(), cmp);
	sz[u] = 0;
	FOR(i, 0, son.size()){
		int v = son[i];
		dp[u] += sz[u];
		sz[u] += sz[v];
	}
	sz[u] += a[u];
	return;
}

int main(){
	scanf("%d", &n);
	FOR(i, 0, n){
		scanf("%d%d", a + i, p + i);
		if(~p[i])
			g[p[i]].PB(i);
	}
	
	FOR(i, 0, n){
		if(!~p[i]){
			dfs(i, p[i]);	
			ans += dp[i];
		}
	}
	
	printf("%lld\n", ans);
	return 0;
}
accuracy: 1
time_ms: 450
memory_kb: 225964
final_rank: 15

code_snippet: #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn=1e6+5;
int a[maxn][2],b[maxn],bl;
vector<int> e[maxn];
vector<int> te[maxn];
long long tot=0;
long long dfs(int node)
{
	if (e[node].size()==0)
		return a[node][0];
	//printf("good");
	long long temp;
	long long sum=0,sum1=0;
	long long mx=0;
	int l=e[node].size();
	for (int i=0;i<l;i++)
	{
		temp=dfs(e[node][i]);
		te[node].push_back(temp);
		sum+=temp;
		if (temp>mx)
			mx=temp;
	}
	sort(te[node].begin(),te[node].end());
	for (int i=0;i<l;i++)
	{
		sum1+=te[node][i]*(l-i-1);
	}
	tot+=sum1;
	return sum+a[node][0];
}

int main()
{
	int n;
	scanf("%d",&n);
	bl=0;
	for (int i=0;i<n;i++)
	{
		scanf("%d%d",&a[i][0],&a[i][1]);
		if (a[i][1]!=-1)
			e[a[i][1]].push_back(i);
		else 
			b[bl++]=i;
	}
	for (int j=0;j<bl;j++)
	{
		dfs(b[j]);
	}
	printf("%lld\n",tot);
	return 0;
}
accuracy: 0.3888888888888889
time_ms: 380
memory_kb: 213588
final_rank: 20

code_snippet: #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn=1e6+5;
int a[maxn][2],b[maxn],bl;
vector<int> e[maxn];
vector<int> te[maxn];
long long tot=0;
long long dfs(int node)
{
	if (e[node].size()==0)
		return a[node][0];
	//printf("good");
	long long temp;
	long long sum=0,sum1=0;
	long long mx=0;
	int l=e[node].size();
	for (int i=0;i<l;i++)
	{
		temp=dfs(e[node][i]);
		te[node].push_back(temp);
		sum+=temp;
		if (temp>mx)
			mx=temp;
	}
	sort(&te[node][0],(&te[node][0])+l);
	for (int i=0;i<l;i++)
	{
		sum1+=te[node][i]*(l-i-1);
	}
	tot+=sum1;
	return sum+a[node][0];
}

int main()
{
	int n;
	scanf("%d",&n);
	bl=0;
	for (int i=0;i<n;i++)
	{
		scanf("%d%d",&a[i][0],&a[i][1]);
		if (a[i][1]!=-1)
			e[a[i][1]].push_back(i);
		else 
			b[bl++]=i;
	}
	for (int j=0;j<bl;j++)
	{
		dfs(b[j]);
	}
	printf("%lld\n",tot);
	return 0;
}
accuracy: 0.3888888888888889
time_ms: 370
memory_kb: 213764
final_rank: 19

code_snippet: #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn=1e6+5;
int a[maxn][2],b[maxn],bl;
vector<int> e[maxn];
long long tot=0;
long long dfs(int node)
{
	if (e[node].size()==0)
		return a[node][0];
	//printf("good");
	long long temp[e[node].size()];
	long long sum=0,sum1=0;
	long long mx=0;
	int l=e[node].size();
	for (int i=0;i<l;i++)
	{
		temp[i]=dfs(e[node][i]);
		sum+=temp[i];
		if (temp[i]>mx)
			mx=temp[i];
	}
	sort(temp,temp+l);
	for (int i=0;i<l;i++)
	{
		sum1+=temp[i]*(l-i-1);
	}
	tot+=sum1;
	return sum+a[node][0];
}

int main()
{
	int n;
	scanf("%d",&n);
	bl=0;
	for (int i=0;i<n;i++)
	{
		scanf("%d%d",&a[i][0],&a[i][1]);
		if (a[i][1]!=-1)
			e[a[i][1]].push_back(i);
		else 
			b[bl++]=i;
	}
	for (int j=0;j<bl;j++)
	{
		dfs(b[j]);
	}
	printf("%lld\n",tot);
	return 0;
}
accuracy: 1
time_ms: 380
memory_kb: 192752
final_rank: 8

code_snippet: #pragma comment(linker, "/STACK:1024000000, 1024000000")
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
typedef int  ll;
const int N = 2e6+5;

struct sil
{
    int last,k;
} edge[N];
int top,n,root[N];
ll cost[N],a[N], cnt;
long long ans;
bool flag[N];
bool cmp(const ll a, const ll b) {
    return a > b;
}
void addedge(int x,int y)
{
    edge[++top].last=root[x];
    edge[top].k=y;
    root[x]=top;
}

void qS(int l,int r)
{
    int i=l,j=r;
    ll x=a[(l+r)/2];
    while (i<=j)
    {
        while (a[i]>x) ++i;
        while (a[j]<x) --j;
        if (i<=j)
        {
            a[0]=a[i]; a[i]=a[j]; a[j]=a[0];
            ++i; --j;
        }
    }
    if (l<j) qS(l,j);
    if (i<r) qS(i,r);
}

void dis(int k)
{
    cnt++;
    while(cnt > 2123456) puts("111");
    if (root[k]==-1) return ;
    for (int i=root[k];i!=-1;i=edge[i].last)
    {
        int j=edge[i].k;
        dis(j);
        cost[k]+=cost[j];
    }
    a[0]=0;
    for (int i=root[k];i!=-1;i=edge[i].last) a[++a[0]]=cost[edge[i].k];
    sort(a+1,a+a[0] + 1,cmp);
    for (int i=2;i<=a[0];++i)
        ans+=(ll)(i-1)*a[i];
}

int main()
{
    #ifdef LOCAL
    freopen("in","r",stdin);
    #endif
    scanf("%d",&n);
        cnt = 0;
        memset(root,-1,sizeof root);
        memset(flag,0,sizeof flag);
        top=0;
        int k;
        for (int i=0;i<n;++i)
        {
            scanf("%d%d",&cost[i],&k);
            if (k==-1) flag[i]=true;
            else addedge(k,i);
        }
        ans=0;
        for (int i=0;i<n;++i) if (flag[i]) dis(i);
        printf("%lld\n",ans);
    return 0;
}
accuracy: 1
time_ms: 160
memory_kb: 61304
final_rank: 3

code_snippet: #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
typedef int  ll;
const int N = 2e6+5;

struct sil
{
    int last,k;
} edge[N];
int top,n,root[N];
ll cost[N],a[N], cnt;
long long ans;
bool flag[N];
bool cmp(const ll a, const ll b) {
    return a > b;
}
void addedge(int x,int y)
{
    edge[++top].last=root[x];
    edge[top].k=y;
    root[x]=top;
}

void qS(int l,int r)
{
    int i=l,j=r;
    ll x=a[(l+r)/2];
    while (i<=j)
    {
        while (a[i]>x) ++i;
        while (a[j]<x) --j;
        if (i<=j)
        {
            a[0]=a[i]; a[i]=a[j]; a[j]=a[0];
            ++i; --j;
        }
    }
    if (l<j) qS(l,j);
    if (i<r) qS(i,r);
}

void dis(int k)
{
    cnt++;
    while(cnt > 2123456) puts("111");
    if (root[k]==-1) return ;
    for (int i=root[k];i!=-1;i=edge[i].last)
    {
        int j=edge[i].k;
        dis(j);
        cost[k]+=cost[j];
    }
    a[0]=0;
    for (int i=root[k];i!=-1;i=edge[i].last) a[++a[0]]=cost[edge[i].k];
    sort(a+1,a+a[0] + 1,cmp);
    for (int i=2;i<=a[0];++i)
        ans+=(ll)(i-1)*a[i];
}

int main()
{
    #ifdef LOCAL
    freopen("in","r",stdin);
    #endif
    scanf("%d",&n);
        cnt = 0;
        memset(root,-1,sizeof root);
        memset(flag,0,sizeof flag);
        top=0;
        int k;
        for (int i=0;i<n;++i)
        {
            scanf("%d%d",&cost[i],&k);
            if (k==-1) flag[i]=true;
            else addedge(k,i);
        }
        ans=0;
        for (int i=0;i<n;++i) if (flag[i]) dis(i);
        printf("%lld\n",ans);
    return 0;
}
accuracy: 1
time_ms: 160
memory_kb: 61172
final_rank: 2