Under construction

Still being built. Things may change

Magic Cube

Time limit1sMemory limit2048 MB

Summary
Given an n by n by n cube of numbered small cubes and a list of slice rotations, report which cube ends up at each queried position.
Level

Medium6 of 10

Topics
Simulation, Implementation, Matrix
Solved
No attempts yet

Problem

Imagine you are holding an n×n×nn \times n \times n cube, which is split into n3n^3 smaller cubes labeled from 1 to n3n^3. The axes run left to right for the xx-axis, back to front for the yy-axis, and bottom to top for the zz-axis. For example, a 2×2×22 \times 2 \times 2 cube is labeled as follows.

Bottom layer (z=1z=1):

1 2 
3 4

Top layer (z=2z=2):

5 6 
7 8

In this 2×2×22 \times 2 \times 2 cube, cube 1 is at (1, 1, 1), cube 2 is at (2, 1, 1), cube 3 is at (1, 2, 1), and cube 5 is at (1, 1, 2).

Each time you rotate the cube at slice kk around one of the xx-, yy-, or zz-axes, the (k+1)(k+1)th layer and all layers after kk in that axis's increasing direction rotate along with it.

Input

The first line contains two integers nn (2≤n≤1 0002 \leq n \leq 1\,000) and mm (1≤m≤2 0001 \leq m \leq 2\,000), the size of the cube and the number of operations.

Each of the next mm lines describes one operation in one of the following forms.

  • x, θ\theta, kk: Rotate slices k+1k+1 through nn by θ\theta degrees counterclockwise around the xx-axis.
  • y, θ\theta, kk: Rotate slices k+1k+1 through nn by θ\theta degrees counterclockwise around the yy-axis.
  • z, θ\theta, kk: Rotate slices k+1k+1 through nn by θ\theta degrees counterclockwise around the zz-axis.
  • q x y z: Query. Output the cube at location (x,y,z)(x, y, z).

For the first three operations, 0≤k≤n−10 \leq k \leq n-1 and θ∈{90,180,270,360}\theta \in \{90, 180, 270, 360\} are guaranteed. For queries, (x,y,z)(x, y, z) is the location, with 1≤x,y,z≤n1 \leq x, y, z \leq n. At least one query is guaranteed. The cube is not reset between operations, so rotations accumulate.

Output

For each query operation, output the number of the cube at the given location, one per line.

Examples3

  1. Example 1

    Input
    2 8
    x 360 1
    y 360 1
    q 1 1 2
    z 90 1
    x 360 1
    q 1 2 1
    q 2 1 1
    q 2 2 2
    
    Expected output
    5
    3
    2
    7
    
  2. Example 2

    Input
    2 7
    x 180 1
    q 1 1 1
    q 1 1 2
    y 270 1
    q 2 1 1
    q 2 1 2
    q 2 2 1
    
    Expected output
    1
    5
    8
    4
    2
    
  3. Example 3

    Input
    3 7
    y 270 1
    q 1 1 1
    q 1 2 3
    z 360 2
    q 3 2 1
    q 2 2 2
    q 3 3 3
    
    Expected output
    1
    4
    24
    14
    25