Big Table
Time limit4sMemory limit128 MB
Each row of a huge table repeats a short digit period; answer rectangle-sum queries without materializing the table.
- Level
Medium6 of 10
- Topics
- Prefix sum, Math, Implementation, Array
- Solved
- No attempts yet
Problem
Mirko and Slavko are always playing some game. They got bored of every existing one, so they decided to invent their own. Mirko imagines a large table of single-digit numbers and writes it down, and Slavko has to answer questions of the form "What is the sum of the numbers in this rectangle?" as fast as he can.
So that Mirko does not have to write out every number of the imagined table, the two agreed on the following. Each row of the table is built by concatenating the row's base period many times and then discarding elements from the end until the row is exactly as wide as the table.
Input
The first line contains and (), the number of rows and the number of columns of the table.
The next lines contain the base periods of the rows, from the top row down. Each period consists of at most digits from 0 to 9, written one after another without spaces.
The next line contains (), the number of questions Slavko has to answer.
Each of the following lines contains four integers ( and ) that describe a rectangle in which Slavko has to find the sum of the numbers. and give the top-left cell of the rectangle (row , column ), and and give the bottom-right cell. Rows are numbered 1 to from top to bottom, and columns are numbered 1 to from left to right.
Output
Print lines with Slavko's answers in the order of the questions, exactly one number per line.
Hint
The periods in the first sample input describe this table:
1111111111
0404040404
1231231231
9898989898
Slavko has to answer a single question, which asks for the sum of all numbers in the table. That sum is 134.