#graph403. 电报

电报

Telegram

Problem Source

JOISC 2016 Day 3

Problem Description

There are NN points. Each point has out-degree exactly 11. You are given, for each point, the point AiA_i it initially points to, and the cost CiC_i required to change where this point points.

Find the minimum total cost needed to make all points strongly connected.

Input Format

The first line contains one integer N(1≤N≤105)N(1\leq N\leq 10^5), the number of points.

The following NN lines each contain two integers $A_i, C_i(1\leq A_i\leq N, A_i\neq i, 1\leq C_i\leq 10^9)$.

Output Format

Output one line: the minimum cost to make all points strongly connected.

Sample Input

4
2 2
1 4
1 3
3 1

Sample Output

4

Constraints

1≤N≤1051\leq N\leq 10^5; 1≤Ai≤N1\leq A_i\leq N, Ai≠iA_i\neq i; 1≤Ci≤1091\leq C_i\leq 10^9.

Hint

  • The given graph is a functional graph (every vertex has out-degree 1), so it consists of directed cycles with trees feeding into them. For the whole graph to be strongly connected, all NN vertices must lie on a single directed cycle; the answer is the minimum cost to reorient some edges so that this happens.