Paper Folding
InterviewTime limit0.5sMemory limit512 MB
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 , folding it times vertically and 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 holes. For example, fold a square with side length 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 giving the paper size, the folding order, and the hole position, write a program that prints the positions of the holes in the grid.
Input
The first line gives .
The second line gives 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 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 lines; line gives the numbers of the holes in row of the grid from left to right, separated by spaces.
Constraints
- The paper is folded exactly times horizontally and times vertically.