Fortune telling with sticks

Given an n by m letter grid and p query words, find for each word the longest contiguous substring that can be placed along a row or column in one of four directions.

Medium6Brute forceImplementationStringArrayNo attempts yetTime limit2sMemory limit512 MB

Problem

Youngsun is a sham fortune teller. She tells fortunes with a very simple method and uses it to decide how much luck a person has.

Each cell of an n×mn \times m grid holds one letter. A visitor writes down any word of length kk. Youngsun lays the word over the grid so that a contiguous part of the word matches the letters of the grid for as long a stretch as possible, and the length of that matched contiguous part decides the amount of luck.

The word is laid in a straight line parallel to the rows or the columns, and its letters can run in any of the four directions: up, down, left, or right. Letters that do not match are allowed to hang outside the grid.

For example, take the grid below, where (r,c)(r, c) is the cell in row rr and column cc.

ABCDE
FGHIJ
KLMNO
PQRST
UVWXY

For the word AHMRVP, the contiguous part HMR can be laid from (2,3)(2,3) to (4,3)(4,3). For the word JEHGFP, the contiguous part HGF can be found from (2,3)(2,3) to (2,1)(2,1).

Youngsun is a sham, but her fortunes happen to come true, so she is surprisingly popular. Today she has to read the fortunes of pp people, but she is off spending the money she earned from fortune telling. Find each word in the grid on her behalf.

Input

The first line contains the grid size nn and mm. (1n,m1001 \le n, m \le 100)

Each of the next nn lines contains the mm letters of one grid row, without spaces.

The next line contains the number of visitors pp and the word length kk. (1p1000001 \le p \le 100\,000, 1k301 \le k \le 30)

Each of the next pp lines contains the kk letters of the word one visitor wrote, without spaces.

Every letter in the grid and in the words is an uppercase English letter.

Output

For each word, in input order and one per line, print the length of the longest contiguous part of the word that can be laid over the grid so that it matches. If no letter of the word appears in the grid, print 00.