Under construction

Still being built. Things may change

Find String in a Grid

Time limit5sMemory limit512 MB

Summary
For each query string, count the right-then-down paths in a 500 by 500 grid that spell it out, with up to 200000 queries.
Level

Medium7 of 10

Topics
String matching, Trie, Hash map
Solved
No attempts yet

Problem

You have a grid GG with RR rows (numbered from 1 to RR, top to bottom) and CC columns (numbered from 1 to CC, left to right). Each cell holds one uppercase character. The character in row rr and column cc is Gr,cG_{r,c}. You also have QQ strings made of uppercase characters. For each string, count the number of occurrences of the string in the grid.

An occurrence of string SS is counted when SS can be built by starting at a cell, moving right 0 or more times, and then moving down 0 or more times. Two occurrences are different if the sets of cells used to build the string are different. Formally, for each string SS, count the tuples (r,c,Δr,Δc)(r, c, \Delta r, \Delta c) that satisfy:

1≤r≤R,r≤r+Δr≤R,1≤c≤C,c≤c+Δc≤C1 \le r \le R, \quad r \le r + \Delta r \le R, \quad 1 \le c \le C, \quad c \le c + \Delta c \le C

and

S=Gr,cGr,c+1⋯Gr,c+ΔcGr+1,c+Δc⋯Gr+Δr,c+ΔcS = G_{r,c}G_{r,c+1}\cdots G_{r,c+\Delta c}G_{r+1,c+\Delta c}\cdots G_{r+\Delta r,c+\Delta c}

Input

The first line contains three integers RR, CC, and QQ (1≤R,C≤5001 \le R, C \le 500, 1≤Q≤200 0001 \le Q \le 200\,000). The next RR lines each contain CC uppercase characters. The cc-th character on the rr-th line is Gr,cG_{r,c}. The next QQ lines each contain one string SS of uppercase characters. Each string has length at least 1 and at most 200 000, and the total length of all QQ strings is at most 200 000.

Output

For each query, in input order, print on its own line the number of occurrences of the string in the grid.

Examples2

  1. Example 1

    Input
    3 3 5
    ABC
    BCD
    DAB
    ABC
    BC
    BD
    AC
    A
    
    Expected output
    2
    3
    1
    0
    2
    
  2. Example 2

    Input
    2 3 3
    AAA
    AAA
    A
    AAA
    AAAAA
    
    Expected output
    6
    4
    0