This page is still under construction.

Parts of this page are still being built. What you see may change.

Turning a Tree

Interview

Time limit1sMemory limit1024 MB

Summary
Reroot a given ordered tree at a specified leaf so the counter-clockwise order of neighbors at each node stays the same, then print the new tree.
Level

Medium6 of 10

Topics
Tree, DFS, Implementation, Recursion
Solved
No attempts yet

Problem

You are given a tree whose nodes are numbered 1…N1 \dots N. Node 11 is the root, and for every node the ordered list of its children (from left to right) is given.

Lift a leaf KK of this tree so that it becomes the new root, keeping every edge intact — in particular, keeping the relative rotational order of the edges around each node unchanged. Output the resulting tree.

For example, starting from the tree on the left below and making the leaf 33 the new root, we obtain the tree in the middle. The tree on the right would be wrong: around node 11 the neighbours, read counter-clockwise, are 2,3,42, 3, 4 in the original tree, but 2,4,32, 4, 3 there.

    1      3       3
   /|\     |       |
  2 3 4    1       1
          / \     / \
         4   2   2   4

Here a tree is a connected acyclic graph and node 11 is its root; see Tree (data structure).

Input

The first line contains two integers: the number of nodes NN (1≤N≤10 0001 \le N \le 10\,000) and the index KK of the leaf that becomes the new root (1≤K≤N1 \le K \le N).

Each of the next NN lines describes one node of the original tree. The (i+1)(i+1)-th line begins with mim_i, the number of children of node ii, followed by the indices of those mim_i children listed from left to right.

Output

Print exactly NN lines describing the new tree, using the same per-node format as the input. The ii-th line begins with the number of children of node ii in the new tree, followed by those children listed from left to right.

Hint

Take the first example, where leaf 33 of the star (node 11 with children 2,3,42, 3, 4) becomes the new root:

  1. Node 11 now has 22 children: nodes 44 and 22, in this order.
  2. Node 22 has no children.
  3. Node 33 has 11 child: node 11.
  4. Node 44 has no children.

Examples1

  1. Example 1

    Input
    4 3
    3 2 3 4
    0
    0
    0
    
    Expected output
    2 4 2
    0
    1 1
    0