#P13854. [CERC 2023] Jumbled Stacks

[CERC 2023] Jumbled Stacks

题目描述

We are given a set of nn cards, labelled from 11 to nn, which are distributed into kk stacks S1,S2,,SkS_1, S_2, \ldots, S_k. Each stack has a limited capacity: the ii-th stack, SiS_i, can contain at most CiC_i cards. The only way we can manipulate these cards is by taking the top card of a stack and moving it to the top of some other stack (as long as this wouldn’t 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 we stack together all the stacks from S1S_1 at the bottom to SkS_k at the top, the cards should be ordered from smallest to largest, with 11 at the bottom and nn at the top.

It is guaranteed that $n \leq \left( \sum_{i=1}^{k} C_i \right) - \max_{1 \leq i \leq k} C_i$.

Suppose we had n=6n = 6 cards on k=3k = 3 stacks, with capacities C1=4C_1 = 4, C2=C3=3C_2 = C_3 = 3, and with the following initial state: S1=[2,3,0,0]S_1 = [2, 3, 0, 0] (from bottom to top; 00 indicates an empty slot), S2=[4,1,6]S_2 = [4, 1, 6], S3=[5,0,0]S_3 = [5, 0, 0]. Then the desired end state is S1=[1,2,3,4]S_1 = [1, 2, 3, 4], S2=[5,6,0]S_2 = [5, 6, 0] and S3=[0,0,0]S_3 = [0, 0, 0].

输入格式

The first line contains two integers, nn (the number of cards) and kk (the number of stacks), separated by a space. The remaining kk lines describe the initial state of the stacks; the ii-th of these lines describes SiS_i and contains Ci+1C_i + 1 integers, separated by spaces. The first of these integers is CiC_i (the capacity of the stack SiS_i), the rest of them are the labels of the cards on SiS_i, from bottom to top. If the stack SiS_i contains fewer than CiC_i cards (it could even be empty), the last few integers in the line will be 00.

输出格式

Print a sequence of moves that bring the stacks into the desired end state. For each move, output a line containing two integers, separated by a space: first the number of the stack from which the card is being moved and then the number of the stack to which it is being moved (the stacks are numbered from 11 to kk; the destination stack must not be the same as the source stack). The number of moves must not exceed 10510^5. After the end of the sequence of moves, print a line containing “0 0” (without the quotation marks). If there are several possible solutions, you may output any of them.

6 3
4 2 3 0 0
3 4 1 6
3 5 0 0
2 3
2 3
1 2
1 2
3 1
2 1
2 1
3 2
3 1
2 3
1 3
2 1
3 2
3 2
0 0

提示

Comment

This is the example discussed earlier in the problem statement. The sample output shows a sequence of 14 moves which bring the stacks into the desired end state.

Input limits

  • 1n1001 \leq n \leq 100
  • 3k1003 \leq k \leq 100
  • 1Cin1 \leq C_i \leq n