Hosuk Fell into String Hell
Time limit1sMemory limit512 MB
Count, for each of K query strings, how many move sequences on a torus grid walk through cells spelling that string, where revisits are allowed.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Brute force, Matrix, Implementation
- Solved
- No attempts yet
Problem
A summer day when the rain fell all day long and the world swayed, and the clouds swallowed the sun so that no one could tell night from day
Hosuk fought off sleep but lost to his heavy eyelids. When he came to, the world had a floor covered in grid-shaped tiles, and each tile had one lowercase alphabet letter written on it. Filled with fear, he ran madly forward looking only ahead, searching for an end, but this world had none. Tired from running, he lay down on the floor, and in the sky these words drifted on blood-red clouds.
- This world is a grid with rows and columns. Each cell has a letter written on it, and the grid is connected in a torus shape. Let the top-left cell be and the bottom-right cell be .
- You can start at any cell and move one cell at a time to a horizontally, vertically, or diagonally adjacent cell. You are allowed to visit cells you have already passed through again.
- Starting with the alphabet of the cell you start at, you can concatenate the alphabet written on each cell you move to in order to build a string.
- I am the god of this place, and I will tell you strings that I like. For each string, you must answer correctly the number of ways you can build it, and then you will return to your world.
- When counting the number of ways, a different visit order is a different case. That is, going and going are different cases.
Hosuk looked at the sky and shouted, "Tell me what a torus is!" The blood-red clouds scattered and gathered again, then drew the following words.
- If you go up from row 1, you go to row , and the reverse is also possible.
- If you go left from column 1, you go to column , and the reverse is also possible.
- The same rule applies to diagonal directions.
- I will draw the following picture in the sky with clouds, so let it help you understand.
- For example, if you go up from , you go to ; if you go left, you go to ; and if you go diagonally up-left, you go to .

Given the information of the grid that makes up the world and strings, find the answers Hosuk must give.
Input
The first line gives the grid dimensions and and the number of strings the god likes, .
The next lines each give lowercase alphabet letters with no spaces. The first of these lines is the information for row 1, and the -th line is the information for row .
Then lines each give a string the god likes. All consist of lowercase alphabet letters.
Output
Over lines, print in order the number of ways to build each string the god likes.
Constraints
- , and and are positive integers.
- , and is a positive integer.
- length of a string the god likes
- Strings the god likes may be duplicated.