Each of Bessie’s N (2≤N≤105) bovine buddies (conveniently labeled 1…N) owns her own farm. For each 1≤i≤N, buddy i wants to visit buddy a_i (a_i=i).
Given a permutation (p_1,p_2,…,p_N) of 1…N, the visits occur as follows.
For each i from 1 up to N:
Compute the maximum possible number of moos after all visits, over all possible permutations p.
The first line contains N.
For each 1≤i≤N, the i+1-st line contains two space-separated integers a_i and v_i.
A single integer denoting the answer.
Note that the large size of integers involved in this problem may require the use of 64-bit integer data types (e.g., a "long long" in C/C++).
If p=(1,4,3,2) then
This gives a total of 10+30=40 moos.
On the other hand, if p=(2,3,4,1) then
This gives 20+30+40=90 total moos. It can be shown that this is the maximum possible amount after all visits, over all permutations p.