Arrange N cards so exactly K are false, where each card claims at least a_i cards below it are false; output the specified canonical arrangement or -1.
Medium6GreedySortingImplementationMathInterviewNo attempts yetTime limit2sMemory limit512 MBYou have a deck of N cards. Card i carries the claim "at least ai of the cards below this one are false".
Once the cards are stacked in a line, every claim can be checked against the stack. A card whose claim holds is true, and a card whose claim fails is false. Whether a card is true or false depends only on how many false cards lie below it.
Find an order that stacks all N cards so that exactly K of them are false. Such an order might not exist at all.
The first line contains the integers N and K (1≤N≤5×105, 0≤K≤N).
Each of the next N lines contains one integer ai (0≤ai≤5×105).
Several orders can satisfy the condition, so a single answer is fixed by the following rule.
Sort the N numbers written on the cards in non-decreasing order. Place the N−K smallest on top of the deck in that non-decreasing order, then place the remaining K below them in non-increasing order. If this deck holds exactly K false cards, print its N numbers on one line separated by single spaces, from the top card to the bottom card. Otherwise print -1.
If any order at all leaves exactly K false cards, this deck is one of them.
Decide the claims from the bottom of the deck upward. Take the deck holding 0, 1, 3, 3, 2 from top to bottom.
The bottom card reads 2 and has no false card below it, so its claim fails and the card is false. The card above it reads 3 and has only 1 false card below it, so it is false. The next card reads 3 and has 2 false cards below it, so it is false. The next card reads 1 and has 3 false cards below it, so it is true. The top card reads 0 and is true. This deck holds 3 false cards in total.