Paint by Letters
Time limit2sMemory limit512 MB
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 rectangle of cells. Rows are numbered from top to bottom, and columns are numbered from left to right (). 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 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 candidates (). Each candidate is given by four integers , , , and , and it denotes the subrectangle of all cells with row in the range to inclusive and column in the range to 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 , , and .
Each of the next lines contains a string of uppercase letters, giving the desired colors for one row of the canvas.
Each of the next lines contains four space-separated integers , , , and , describing one candidate subrectangle (, ).
Output
For each of the candidates, print the answer on its own line.