HDU 4758 Walk Through Squares
Problem Description
On the beaming day of 60th anniversary of NJUST, as a military college which was Second Artillery Academy of Harbin Military Engineering Institute before, queue phalanx is a special landscape.
Here is a rectangle, and this one can be divided into squares which are of the same size. As shown in the figure below.
01–02–03–04
||||&|| &||
05–06–07–08
||||&|| &||
09–10–11–12
Consequently, we have nodes, which are all connected to their adjacent nodes. And actual queue phalanx will go along the edges.
The ID of the first node,the one in top-left corner, is . And the ID increases line by line first, and then by column in turn, as shown in the figure above.
For every node, there are two viable paths:
(1) go downward, indicated by D;
(2) go right, indicated by R.
The current mission is that, each queue phalanx has to walk from the left-top node No.1 to the right-bottom node whose ID is .
In order to make a more aesthetic marching, each queue phalanx has to conduct two necessary actions. Let’s define the action:
An action is started from a node to go for a specified travel mode.
So, two actions must show up in the way from to .
For example, as to a rectangle, figure below.
01–02–03–04
||||&|| &||
05–06–07–08
||||&|| &||
09–10–11–12
Assume that the two actions are (1)RRD (2)DDR
As a result , there is only one way : RRDDR. Briefly, you can not find another sequence containing these two strings at the same time.
If given the and two actions, can you calculate the total ways of walking from node No.1 to the right-bottom node?
Input
The first line contains a number , ( is about , including small test cases and large ones) denoting the number of the test cases.
For each test cases,the first line contains two positive integers and (For large test cases,, and for small ones ) . denotes the row number and denotes the column number.
The next two lines each contains a string which contains only R and D. The length of string will not exceed . We ensure there are no empty strings and the two strings are different.
Output
For each test cases,print the answer mod in one line.
Sample Input
2
3 2
RRD
DDR
3 2
R
D
Sample Output
1
10
Idea
两种 ,可以视为两个模式串,利用两个模式串可以建立 AC 自动机。
从坐标 走向 ,行走路线组成的字符串有多种,而对于两个模式串的存在情形,只存在四种状态,不妨进行状态压缩。00 代表两个模式串都不包含,01 代表仅包含第一个模式串,10 代表仅包含第二个模式串,11 代表两个模式串都包含。
插入字符串时,在字符串结尾标记改节点的状态,第一个模式串结尾标记为 01,第二个模式串结尾标记为 10。建立 AC 自动机时,利用 指针的性质,$\mathrm{fail}_x$ 指向节点 所指代字符串的一个后缀,节点 的状态应当与节点 $\mathrm{fail}_x$ 的状态叠加。如下图所示,DRD 为第一个模式串,RD 为第二个模式串;插入模式串时,节点 的状态为 01,节点 的状态为 10;叠加后,节点 的状态为 11,节点 的状态仍为 10。
采用状态压缩DP的方式, 表示实际走至坐标 ,位于 AC 自动机的节点 ,行走路线组成字符串状态为 时的总方案数。由于只会出现 D 和 R 两个字符,将 D 映射为 ,R 映射为 ;那么就存在状态转移函数 和 。考虑状态转移,若要向下走,则坐标转移至 ,此时位于 AC 自动机的节点 ,将状态 与节点 的状态叠加即为向下走一步后,行走路线组成的字符串的状态;向右走同理。走到 时,可以停留在AC自动机的任意节点,最后得到的 即为答案。
Code
1 |
|
Postscript
测试数据中, 的位置反了,这一点在原题的 板块提到。