Settling Salaries
Time limit1sMemory limit512 MB
Workers on a ring compare contract pay to cash received and settle every balance with the fewest transfers between neighbors.
- Level
Hard8 of 10
- Topics
- Greedy, Prefix sum, Hash map
- Solved
- No attempts yet
Problem
Bajtosoft employs workers. Because the projects it develops are confidential, not all of them know one another. Two workers know each other only if they handle consecutive stages of the same project.
Every project is developed sequentially: worker (the team lead) makes the first draft and passes it to worker ; after finishing their part, worker passes the result to worker , and so on, until the project reaches worker , who completes it and hands the finished product back to the team lead (worker ).
Each worker has a salary written into their contract. However, the company does not always honor the contract exactly. It always pays out the correct total amount, but not always to the right people: it often happens that one person receives less than their contract guarantees while another receives more.
Luckily the workers are honest, so they agreed that after every payout they will settle the amounts among themselves so that in the end everyone receives exactly what their contract guarantees.
There is just one catch: money can be transferred only between workers who know each other. That is, for every , worker may give money to or receive money from only workers and ; worker may transact with workers and ; and worker may transact with workers and .
Because each such settlement requires many transactions, the Bajtosoft workers have asked you, an independent programmer, to write a program that after each payout determines the minimum number of transactions needed to settle the accounts.
We assume that in these transactions workers use only the money they received from the company in the given payout together with the money they received from other workers in earlier transactions.
Input
The first line of standard input contains a single integer (), the number of Bajtosoft workers.
Each of the next lines contains two integers and (), separated by a single space: the salary of the -th worker guaranteed by the contract and the amount they actually received (both in bytalers). You may assume that .
Output
Print, in the first and only line of standard output, a single integer: the minimum number of transactions between workers who know each other that reaches a state where every worker ends up (after all transactions) with exactly the amount guaranteed by their contract.
If no set of transactions can reach such a state, print the single word "NIE".
Hint
Explanation of the sample: All salaries are settled in two steps: worker gives worker one bytaler, and worker gives worker three bytalers.