#P6486. [COCI 2010/2011 #4] DUGOVI

[COCI 2010/2011 #4] DUGOVI

Description

In a small town, there are nn residents. Each resident has borrowed some money from exactly one other resident.

Now it is time to repay the debts. But the problem is that everyone has spent all their money; that is, nobody is able to repay their debt. This leads to many conflicts.

The mayor decides to solve this problem. He plans to give some money to a part of the residents so that they can use it to repay their debts. However, once some residents receive money, a chain reaction begins.

For example, AA receives money from the mayor. AA quickly uses this money to repay the debt to BB. Then BB repays the debt to CC, and so on.

Here, if BB does not have enough money to pay off the debt at once, then he will keep the money temporarily until he has enough; if there is money left after repaying the debt, BB will also keep it. (The behavior of BB applies to any person.)

Another example: if two residents in the town owe each other 100100 dollars, then the mayor only needs to give 100100 dollars to one of them, and both debts will be settled.

You need to write a program to compute: what is the minimum amount of money the mayor must pay to some residents to settle all debts?

Input Format

The first line contains an integer nn, the number of residents in the town.

The next nn lines each contain two integers Ai,BiA_i, B_i, meaning that person ii owes person AiA_i BiB_i dollars.

Residents are numbered from 11 to nn.

Output Format

Output one line with one integer, the minimum amount the mayor must pay.

4
2 100
1 100
4 70
3 70
170
3
2 120
3 50
2 80
150
5
3 30
3 20
4 100
5 40
3 60
110

Hint

Constraints

For 100%100\% of the testdata, it is guaranteed that 2n2×1052\le n\le 2\times 10^5, 1Ain1\le A_i\le n and AiiA_i\neq i, 1Bi1041\le B_i\le 10^4.

Notes

Translated from COCI2010-2011 CONTEST #4 T5 DUGOVI

Translated by ChatGPT 5