#K101. Balance the Books
Balance the Books
Balance the Books
You are given n children and an integer b representing the target number of books each child should have. Initially, the i-th child has a certain number of books provided in an array. You are allowed to redistribute books between children using a "transfer" operation. Each transfer is defined by a triplet of integers: (from, to, amount), where one child donates amount books to another child.
The goal is to achieve a state where each child has exactly b books. Formally, let \(n\) be the number of children and the initial books be given as an array \(A = [a_1, a_2, \dots, a_n]\). The necessary condition for a solution is that the total number of books satisfies
[ \sum_{i=1}^{n} a_i = n \times b ]
If this condition fails, it is impossible to balance the books. Moreover, you are given a maximum allowed number of transfers. If balancing requires more than the allowed transfers, the answer should be "NO".
If a solution exists within the allowed number of transfers, output the number of transfers performed and list each transfer operation. Children are numbered from 1 to n.
inputFormat
The input is given via standard input with the following format:
- The first line contains three space-separated integers: n (the number of children), b (the target books per child), and transfers (the maximum allowed number of transfers), where \(1 \le n \le 300\), \(0 \le b \le 10^9\), and \(1 \le transfers \le n^2\).
- The second line contains n space-separated integers representing the number of books each child currently has.
outputFormat
If it is possible to balance the books within the allowed number of transfers, output the number of transfers performed on the first line. Then, for each transfer, output a line with three space-separated integers representing from (donor child id), to (recipient child id), and the amount of books transferred. If no transfers are needed, simply output 0.
If it is impossible to achieve the target configuration or if the required transfers exceed the allowed number, output a single line containing NO
.
3 4 3
6 2 4
1
1 2 2
</p>