#P11493. [2023省队模拟]数独

[2023省队模拟]数独

题目描述

一个 n×mn\times m 数独是一张包含 m×nm\times n 个区域的网格,其中每个区域包含 n×mn\times m 个格子,因此一个 n×mn\times m 数独共有 nm×nmnm\times nm 个格子。 n×mn\times m 数独的每行、每列、每个区域都恰好包含 1nm1\sim nm 的所有整数。

对于某行或某列,从某个方向开始,依次列出这行(列)的 nmnm 个数字,记得到的序列的第一个数为 XX ,则称这行(列)在这个方向上的 XsumX-sum 为此序列的前 XX 个数之和。

上图列出了一个 4×24\times 2 数独及其所有 XsumX-sum 。例如,第 77 行从右至左依次为 [3,4,1,2,7,8,5,6][3,4,1,2,7,8,5,6] ,其中第一个数是 33 ,则第 77 行的从右至左的 XsumX-sum3+4+1=83+4+1=8

给定正整数 n,mn,m ,一个方向 dd 和一个下标 xx ,求字典序最小的 2n×2m2^n\times 2^m 数独的第 xx 行(列)在方向 dd 上的 XsumX-sum

记数独 aa 的第 ii 行第 jj 列为 ai,ja_{i,j} 。称数独 aa 的字典序小于数独 bb ,当且仅当存在 x,yx,y ,使得对于所有 i<xi < xai,j=bi,ja_{i,j}=b_{i,j} ,对于所有 j<yj < yax,j=bx,ja_{x,j}=b_{x,j} ,且 ax,y<bx,ya_{x,y} < b_{x,y} 。上图即为字典序最小的 4×24\times 2 数独。

输入格式

本题有多组数据。第一行一个整数 TT ,表示数据组数。对于每组数据:

仅一行,依次为两个整数 n,mn,m ,一个字符串 dd 和一个整数 xx 。其中 n,mn,m 表示数独的大小为 2n×2m2^n\times 2^mdd 为 " leftleft "," rightright "," toptop " 和 " bottombottom " 中的一个,分别表示从左至右、从右至左、从上至下、从下至上; xx 为行或列的下标。

输出格式

对于每组数据,输出一行一个整数,表示字典序最小的 2n×2m2^n\times 2^m 数独的第 xx 行(列)在方向 dd 上的 XsumX-sum
注意答案可能会超过 unsigned long long\texttt{unsigned long long} 的范围,你可以使用 \texttt{__int128_t} 等数据类型。

数据范围

对于 25%25\% 的数据, n+m8n+m\le 8
另有 5%5\% 的数据, x=1x=1x=2n+mx=2^{n+m}
另有 15%15\% 的数据, dd 为 " leftleft " 或 " rightright ", x2nx\le 2^n
另有 15%15\% 的数据, dd 为 " leftleft " 或 " rightright "。
另有 20%20\% 的数据, dd 为 " toptop " 或 " bottombottom ", x2mx\le 2^m
另有 10%10\% 的数据, dd 为 " toptop " 或 " bottombottom "。
对于 100%100\% 的数据, 1T1051\le T\le 10^51n,m301\le n,m\le 30dd 为 " leftleft "," rightright "," toptop " 和 " bottombottom " 中的一个, 1x2n+m1\le x\le 2^{n+m}

输入样例 1

4
2 1 top 1
2 1 bottom 2
2 1 left 3
2 1 right 4

输出样例 1

1
34
27
3

输入样例 2

4
11 19 top 1053766555
12 26 top 230781535210
14 10 right 8344647
7 30 right 70120568170

输出样例 2

565741033271081135
31719572400444316026492
112693473538824
477453505821905419941