Puzzle: X-Sums Sudoku

아직 제출이 없습니다시간 제한4초메모리 제한1024 MB

문제

An n×mn\times m sudoku puzzle is a grid consisting of m×nm\times n regions, and each region contains n×mn\times m cells. Hence an n×mn\times m sudoku puzzle contains nm×nmnm\times nm cells. Every integer from 11 to nmnm occurs exactly once in each row, each column, and each region of an n×mn\times m sudoku puzzle.

Listing the integers in a row or a column starting from some direction as a sequence of length nmnm, XX is the first integer of the sequence, and X-sum is the sum of the first XX integers of the sequence.

The above figure is a 4×24\times 2 sudoku puzzle with X-sums. The 77-th row listed from right to left is \[3,4,1,2,7,8,5,6]\[3,4,1,2,7,8,5,6] and the first integer XX is 33, so the X-sum of the 77-th row from the direction right is 8=3+4+18=3+4+1.

Given two positive integers nn and mm, a direction dd, and an index xx, you need to find the X-sum of the xx-th row or xx-th column from the direction dd in the lexicographically smallest 2n×2m2^n\times 2^m sudoku.

Denoting a_i,ja\_{i,j} as the ii-th row and the jj-th column of a sudoku puzzle aa, a sudoku puzzle aa is lexicographically smaller than a sudoku puzzle bb of the same size if there exists ii and jj satisfying that a_i,j\<b_i,ja\_{i,j}\<b\_{i,j}, that a_x,y=b_x,ya\_{x,y}=b\_{x,y} for all x\<ix\<i, and that a_x,y=b_x,ya\_{x,y}=b\_{x,y} for all x=ix=i and y\<jy\<j. You can find that the above is the lexicographically smallest 4×24\times 2 sudoku puzzle.

입력

There are multiple test cases. The first line of input contains an integer TT(1T1051\le T\le 10^5), the number of test cases.

For each test case:

The only line contains two integers nn and mm (1n1\le n, m30m\le 30), a string dd, and an integer xx (1x2n+m1\le x\le2^{n+m}). Here, 2n×2m2^n\times 2^m is the size of the sudoku puzzle; dd is the direction of X-sum, and it is one of "left", "right", "top", and "bottom"; xx is the index of a row or a column.

출력

For each test case:

Output an integer: the X-sum of the xx-th row or xx-th column from the direction dd in the lexicographically smallest 2n×2m2^n\times 2^m sudoku.

Note that the answer may exceed 26412^{64}-1. Consider using __int128_t in C++, BigInteger in Java or Kotlin, or int in Python.