Jumbled Stacks
Time limit1sMemory limit1024 MB
Move top cards between capacity-limited stacks so cards 1 to n end up sorted bottom to top, packed into the lowest-indexed stacks.
- Level
Medium6 of 10
- Topics
- Simulation, Stack, Implementation
- Solved
- No attempts yet
Problem
We are given a set of cards, labelled from 1 to , which are distributed into stacks . Each stack has a limited capacity: the -th stack, , can contain at most cards. The only way to manipulate these cards is to take the top card of a stack and move it to the top of some other stack, as long as this does not exceed the capacity of the destination stack.
Using a sequence of such moves, we would like to rearrange the cards so that the first few stacks (0 or more) with the smallest indices are filled to capacity, the stack immediately after them is not filled to capacity (and may even be empty), and all stacks after that are completely empty. Moreover, if you stack all the stacks from at the bottom to at the top, the cards must be ordered from smallest to largest, with at the bottom and at the top.
It is guaranteed that .
Suppose we had cards on stacks, with capacities , , and with the following initial state: (from bottom to top; indicates an empty slot), , . Then the desired end state is , and .
Input
The first line contains two integers, (the number of cards) and (the number of stacks), separated by a space. The remaining lines describe the initial state of the stacks. The -th of these lines describes and contains integers, separated by spaces. The first of these integers is (the capacity of the stack ), and the rest are the labels of the cards on , from bottom to top. If the stack contains fewer than cards (it could even be empty), the last few integers in the line are 0.
Output
Print a sequence of moves that brings the stacks into the desired end state. For each move, output a line with two integers separated by a space: first the number of the stack the card is moved from, then the number of the stack it is moved to. The stacks are numbered from 1 to , and the destination must differ from the source. The number of moves must not exceed . After the last move, print a line containing "0 0" (without the quotation marks). If there are several possible solutions, you may output any of them.
Constraints
Hint
This is the example discussed earlier in the problem statement. The sample output shows a sequence of 14 moves that brings the stacks into the desired end state.