Going Dutch
Time limit2sMemory limit512 MB
Given each person's net balance from the receipts, find the minimum number of money transfers that settles everyone to zero.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Bit manipulation, Backtracking, Greedy
- Solved
- No attempts yet
Problem
You and your friends have just returned from a vacation in the mountains of the Netherlands. Splitting the bill on every expense during the trip is annoying, so you kept all the receipts instead and wrote down who paid how much for whom. Now it is time to settle the bill.
Each of you could take the receipts showing that someone paid something for you and pay that person back. That takes a lot of transactions, and you want to keep up the lazy spirit from the trip. It does not matter who transfers money to whom, as long as everyone's balance is in the end.
Find the least number of transactions needed to settle the score. One transaction moves money from one person to one other person, and assume everyone has enough spare cash to transfer any amount.
Input
The first line contains two integers , the number of people in the group, and , the number of receipts from the trip, with and .
Each of the next lines contains three integers , , with and , a receipt showing that person paid euros for person .
Output
Print a single integer on one line, the least number of transactions necessary to settle all bills.