Under construction

Still being built. Things may change

X-Sums Sudoku

Time limit4sMemory limit1024 MB

Summary
Given n, m, a direction, and an index, find the X-sum of that row or column in the lexicographically smallest 2^n by 2^m sudoku.
Level

Hard8 of 10

Topics
Math, Bit manipulation, Recursion
Solved
No attempts yet

Problem

An n×mn\times m sudoku puzzle is a grid made 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.

List the integers in a row or a column from some direction as a sequence of length nmnm. Let XX be the first integer of the sequence. The X-sum is the sum of the first XX integers of the sequence.

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

Given two positive integers nn and mm, a direction dd, and an index xx, 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.

For two sudoku puzzles aa and bb of the same size, aa is lexicographically smaller than bb if there exist ii and jj such that ai,j<bi,ja_{i,j}<b_{i,j}, ax,y=bx,ya_{x,y}=b_{x,y} for all x<ix<i, and ax,y=bx,ya_{x,y}=b_{x,y} for x=ix=i and y<jy<j.

Input

The first line contains an integer TT (1≤T≤1051\le T\le 10^5), the number of test cases.

Each test case is one line with two integers nn and mm (1≤n,m≤301\le n, m\le 30), a string dd, and an integer xx (1≤x≤2n+m1\le x\le 2^{n+m}). The puzzle size is 2n×2m2^n\times 2^m. The direction dd is one of left, right, top, or bottom. The index xx identifies a row or a column.

Output

For each test case, print one integer on its own line: 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.

The answer can exceed 264−12^{64}-1.

Examples2

  1. Example 1

    Input
    4
    2 1 top 1
    2 1 bottom 2
    2 1 left 3
    2 1 right 4
    
    Expected output
    1
    34
    27
    3
    
  2. Example 2

    Input
    4
    11 19 top 1053766555
    12 26 top 230781535210
    14 10 right 8344647
    7 30 right 70120568170
    
    Expected output
    565741033271081135
    31719572400444316026492
    112693473538824
    477453505821905419941