Flip and Turn

Time limit2sMemory limit64 MB

Summary
Simulate up to 100000 sequential matrix transformations (transpose, flip, rotate) efficiently and output the final matrix.
Level

Medium5 of 10

Topics
Matrix, Simulation, Implementation
Solved
No attempts yet

Problem

You are given a matrix AA of printable characters with mm rows and nn columns. Rows are numbered from 11 by the first index and columns from 11 by the second index. A single operation replaces the current matrix with a new matrix BB according to one of the following rules (the character in backticks is the operation identifier).

  • Transpose over the main diagonal (1): Bj,i=Ai,jB_{j,i} = A_{i,j}
  • Transpose over the anti-diagonal (2): Bn−j+1,m−i+1=Ai,jB_{n-j+1,m-i+1} = A_{i,j}
  • Horizontal flip (H): Bm−i+1,j=Ai,jB_{m-i+1,j} = A_{i,j}
  • Vertical flip (V): Bi,n−j+1=Ai,jB_{i,n-j+1} = A_{i,j}
  • Clockwise rotation by 9090 (A), 180180 (B), or 270270 (C) degrees; the 9090-degree case is Bj,m−i+1=Ai,jB_{j,m-i+1} = A_{i,j}
  • Counterclockwise rotation by 9090 (X), 180180 (Y), or 270270 (Z) degrees; the 9090-degree case is Bn−j+1,i=Ai,jB_{n-j+1,i} = A_{i,j}

You are given a sequence of at most 100,000 operations from this set. Apply them to the matrix in the given order and output the resulting matrix.

Input

The first line contains two integers mm and nn (0<m,n≤3000 < m, n \le 300). Each of the next mm lines contains exactly nn printable characters, where a printable character is a symbol whose ASCII code is between 3333 and 126126 inclusive; these lines contain no other symbols. The following line contains the sequence of operations, each given by its one-character identifier, to be applied from left to right.

Output

Print two integers: the number of rows and the number of columns of the resulting matrix. Then print the resulting matrix in the same format as the input.

Examples5

  1. Example 1

    Input
    3 4
    0000
    a0b0
    cdef
    A1
    
    Expected output
    3 4
    cdef
    a0b0
    0000
    
  2. Example 2

    Input
    1 1
    Q
    ABCXYZ12HV
    
    Expected output
    1 1
    Q
    
  3. Example 3

    Input
    1 5
    hello
    V
    
    Expected output
    1 5
    olleh
    
  4. Example 4

    Input
    5 1
    a
    b
    c
    d
    e
    A
    
    Expected output
    1 5
    edcba
    
  5. Example 5

    Input
    2 3
    abc
    def
    11
    
    Expected output
    2 3
    abc
    def