Finding a Grayscale Image
Time limit10sMemory limit512 MB
Count the R by C windows of A that equal B after a linear brightness change of the form p times A plus q.
- Level
Hard8 of 10
- Topics
- String matching, Matrix, Math
- Solved
- No attempts yet
Problem
A grayscale image has no color. Each pixel of a grayscale image therefore records one number, the brightness of that pixel. In this problem the brightness of a pixel is an integer between and .
A grayscale image of size is pixels arranged in rows and columns. Write for the brightness of the pixel in row and column . (, )
Gyeonggeun has a grayscale image of size and a grayscale image of size . Here and , so is no shorter and no narrower than . Gyeonggeun believes that plagiarized , and wants to count how many parts of resemble .
The counting works like this. First choose one rectangle of pixels inside the grayscale image . The rectangle is determined by the position of the pixel at its top left corner. (, )

The size is fixed, so moving the top left corner moves the whole rectangle with it. For example, take the grayscale image above as and choose a rectangle whose top left corner is . The bottom right corner of that rectangle is .
Whether the chosen rectangle resembles the image is decided by the following rule.
If there are real numbers and such that holds for every and with and , then the rectangle chosen in and the image are similar.
Apply this rule to every rectangle of size in and count the rectangles that are similar to . In other words, apply the rule to every with and , then count the pairs judged similar. Two rectangles of the same size are different when the coordinates of their top left corners differ, no matter what the brightness inside them is.
Help Gyeonggeun and write a program that counts the parts of that are similar to .
Input
The first line contains the number of rows and the number of columns of the grayscale image , separated by a space. ()
The next lines describe the pixels of . The -th of those lines contains integers separated by spaces. The -th integer on the -th line is the brightness of the pixel in row and column of . ()
The next line contains the number of rows and the number of columns of the grayscale image , separated by a space. (, )
The next lines describe the pixels of . The -th of those lines contains integers separated by spaces. ()
Every given pixel brightness is an integer between and .
Output
Print the number of parts of that are similar to .
Hint
When every pixel of has the same brightness, you can take and let be that brightness, so every rectangle of is judged similar.