#P6486. [COCI 2010/2011 #4] DUGOVI
[COCI 2010/2011 #4] DUGOVI
Description
In a small town, there are 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, receives money from the mayor. quickly uses this money to repay the debt to . Then repays the debt to , and so on.
Here, if 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, will also keep it. (The behavior of applies to any person.)
Another example: if two residents in the town owe each other dollars, then the mayor only needs to give 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 , the number of residents in the town.
The next lines each contain two integers , meaning that person owes person dollars.
Residents are numbered from to .
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 of the testdata, it is guaranteed that , and , .
Notes
Translated from COCI2010-2011 CONTEST #4 T5 DUGOVI。
Translated by ChatGPT 5
京公网安备 11011102002149号