Birthday Gift
Time limit1sMemory limit128 MB
Assign integer payments capped by each friend's maximum so the sum equals the gift price while lexicographically minimizing sorted deviations from the fair share, breaking remaining ties by capacity and input order.
- Level
Medium7 of 10
- Topics
- Greedy, Binary search, Sorting
- Solved
- No attempts yet
Problem
Today is Sunyoung's birthday, and her friends have decided to buy her StarCraft II as a birthday gift.
The friends want to split the cost fairly. Because they are not equally well off, no one pays more than the maximum amount they can afford. Everyone pays an integer number of won (fractional amounts are not allowed), and everyone pays at least won.
If the gift costs and there are friends, each person's fair share is . To split the cost fairly, we minimize the maximum over all people of the difference between the amount a person pays and . If several ways tie on this maximum, we then minimize the next largest difference, then the one after that, and so on.
Because each person only has to pay at least won, several payment plans may satisfy the rule above. In that case, a person who can afford more (a larger maximum amount) pays more. If ties still remain, the person earlier in the list pays more.
Given the maximum amount each friend can pay and the price of the gift, write a program that determines how much each person must pay. If there is no way to collect the price of the gift exactly, print IMPOSSIBLE instead.
Input
The first line contains the number of test cases . ()
Each test case consists of two lines. The first line contains the price of the gift and the number of friends , separated by a space. (, ) The second line contains the maximum amounts that each friend can pay, separated by spaces. ()
Output
For each test case, print on one line the amount each person must pay, in the input order, separated by spaces. If there is no fair way to collect the price of the gift, print IMPOSSIBLE on that line instead.