This page is still under construction.

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

Paper Folding

Interview

Time limit0.5sMemory limit512 MB

Summary
Given k, a sequence of 2k folds, and one punched corner of the final unit square, print the full grid of hole positions after unfolding.
Level

Medium6 of 10

Topics
Implementation, Simulation, Divide and conquer, Recursion
Solved
No attempts yet

Problem

There are four ways to fold a square sheet of paper along its center lines, as the figures below show.

  • D: fold in half along the horizontal center line so that the top face covers the bottom face.

  • U: fold in half along the horizontal center line so that the bottom face covers the top face.

  • R: fold in half along the vertical center line so that the left face covers the right face.

  • L: fold in half along the vertical center line so that the right face covers the left face.

Given a square sheet whose side length is 2k2^k, folding it kk times vertically and kk times horizontally (the order does not matter) yields a square whose side length is 1. Punch a hole at one of the four corners of this unit square, as the figure below shows. The hole positions are labeled with numbers as in the figure.

After punching the hole, unfold the paper in the reverse of the folding order, and the paper has 22k2^{2k} holes. For example, fold a square with side length 4(=22)4(= 2^2) in the order <R, D, D, R>, punch a hole at position 3, and unfold the paper; the holes appear as in the figure below.

Given an integer kk giving the paper size, the folding order, and the hole position, write a program that prints the positions of the holes in the 2k×2k2^k \times 2^k grid.

Input

The first line gives kk.

The second line gives 2k2k characters representing the folding methods, separated by spaces. The folding methods D, U, R, L are given as the corresponding uppercase letters.

The third line gives the integer h(0≤h≤3)h(0 \le h \le 3) representing the hole position.

Output

Unfold the folded paper in the reverse of the folding order, then print the positions of the holes in the square as numbers. The output consists of 2k2^k lines; line i(1≤i≤2k)i(1 \le i \le 2^k) gives the numbers of the holes in row ii of the grid from left to right, separated by spaces.

Constraints

  • 1≤k≤81 \le k \le 8
  • The paper is folded exactly kk times horizontally and kk times vertically.

Examples1

  1. Example 1

    Input
    2
    R D D R
    3
    
    Expected output
    0 1 0 1
    2 3 2 3
    0 1 0 1
    2 3 2 3