Monoliteral Polygons

Time limit2sMemory limit128 MB

Summary
Count integer translations of a given rectilinear polygon so it stays inside a lettered grid and covers cells of only one letter.
Level

Hard8 of 10

Topics
Prefix sum, Geometry, Implementation
Solved
No attempts yet

Problem

You are given a table with R rows and C columns. Each cell contains one lowercase English letter, and every cell is a square of the same size.

Coordinates are assigned to the vertices of the cells. The upper-left corner of the table is (0, 0), the upper-right corner is (C, 0), the lower-left corner is (0, R), and the lower-right corner is (C, R).

A polygon inside the table is called monoliteral if it satisfies all of the following conditions.

  1. Every vertex is one of the cell vertices described above.
  2. Every edge is parallel to one of the coordinate axes.
  3. All cells contained inside the polygon have the same letter.

You are given one simple polygon satisfying conditions 1 and 2. You may translate it by an integer distance upward, downward, leftward, rightward, or by a combination of those directions, but you may not rotate it. Count the number of distinct positions where the translated polygon lies completely inside the table and is monoliteral.

Input

The first line contains two space-separated integers R and C. (1 <= R, C <= 500)

Each of the next R lines contains a lowercase English string of length C, describing one row of the table.

The next line contains the number of vertices V of the given polygon. (4 <= V <= 500)

Each of the next V lines contains two integers X and Y, the coordinates of a vertex. (0 <= X <= C, 0 <= Y <= R)

The vertices are given in clockwise order. The given polygon satisfies conditions 1 and 2 from the statement.

Output

Print the number of polygon positions that satisfy the condition.

Examples3

  1. Example 1

    Input
    3 3
    aaa
    aaa
    aaa
    4
    2 0
    2 2
    0 2
    0 0
    
    Expected output
    4
    
  2. Example 2

    Input
    3 3
    aaa
    aba
    aaa
    4
    2 0
    2 2
    0 2
    0 0
    
    Expected output
    0
    
  3. Example 3

    Input
    5 4
    xyyx
    xyyy
    xxyy
    xxxx
    xxxx
    8
    1 3
    1 2
    0 2
    0 0
    2 0
    2 1
    3 1
    3 3
    
    Expected output
    2