Under construction

Still being built. Things may change

Paint by Letters

Time limit2sMemory limit512 MB

Summary
For each query subrectangle, count the connected same-color regions, since each region needs exactly one stroke.
Level

Medium7 of 10

Topics
Graph, Prefix sum, Union-find
Solved
No attempts yet

Problem

Bessie has recently received a painting set. The canvas is an N×MN \times M rectangle of cells. Rows are numbered 1…N1\ldots N from top to bottom, and columns are numbered 1…M1\ldots M from left to right (1≤N,M≤10001\le N,M\le 1000). Once painted, a cell gets one uppercase letter from 'A' to 'Z' as its color. Initially, all cells are uncolored, and a cell cannot be painted more than once.

Bessie has chosen the desired color for each cell. She can paint a set of cells with one color in a single stroke if the set forms a connected component, that is, any cell in the set can reach any other through a sequence of adjacent cells. Two cells are adjacent if they share an edge.

For example, the 3×33 \times 3 canvas below can be colored in four strokes.

AAB
BBA
BBB
...    ..B    AAB    AAB    AAB
... -> ... -> ... -> BB. -> BBA
...    ...    ...    BBB    BBB

Fewer than four strokes cannot produce the result.

Bessie is an avant-garde artist, so she paints only a subrectangle of the canvas. She is considering QQ candidates (1≤Q≤10001\le Q\le 1000). Each candidate is given by four integers x1x_1, y1y_1, x2x_2, and y2y_2, and it denotes the subrectangle of all cells with row in the range x1x_1 to x2x_2 inclusive and column in the range y1y_1 to y2y_2 inclusive.

For each candidate, find the minimum number of strokes needed to paint every cell in the subrectangle with its desired color while leaving all cells outside the subrectangle uncolored. Bessie does not actually paint anything during this process, so the answers for the candidates are independent of each other.

Input

The first line contains NN, MM, and QQ.

Each of the next NN lines contains a string of MM uppercase letters, giving the desired colors for one row of the canvas.

Each of the next QQ lines contains four space-separated integers x1x_1, y1y_1, x2x_2, and y2y_2, describing one candidate subrectangle (1≤x1≤x2≤N1\le x_1\le x_2\le N, 1≤y1≤y2≤M1\le y_1\le y_2\le M).

Output

For each of the QQ candidates, print the answer on its own line.

Examples1

  1. Example 1

    Input
    4 8 9
    ABBAAAAA
    ABAAAABA
    CAADABBA
    AAAAAAAA
    1 1 4 8
    3 5 3 8
    1 3 2 4
    1 4 2 5
    1 1 3 3
    4 4 4 4
    2 6 4 8
    3 5 4 6
    1 6 3 8
    
    Expected output
    6
    3
    2
    1
    4
    1
    3
    2
    2