After a long journey, the super-space-time immigrant ship carrying you finally discovered a planet that seems to be habitable. The planet, named JOI, is a harsh planet with three types of terrain, "Jungle," "Ocean," and "Ice," as the name implies. A simple survey created a map of the area around the planned residence. The planned place of residence has a rectangular shape of M km north-south and N km east-west, and is divided into square sections of 1 km square. There are MN compartments in total, and the compartments in the p-th row from the north and the q-th column from the west are represented by (p, q). The northwest corner section is (1, 1) and the southeast corner section is (M, N). The terrain of each section is one of "jungle", "sea", and "ice". "Jungle" is represented by J, "sea" is represented by O, and "ice" is represented by one letter I.
Now, in making a detailed migration plan, I decided to investigate how many sections of "jungle," "sea," and "ice" are included in the rectangular area at K.
input
Read the following input from standard input.
The integers M and N are written on the first line, separated by blanks, indicating that the planned residence is M km north-south and N km east-west.
The integer K is written on the second line, which indicates the number of regions to be investigated.
The following M line contains information on the planned residence. The second line of i + (1 ≤ i ≤ M) contains an N-character string consisting of J, O, and I that represents the information of the N section located on the i-th line from the north of the planned residence. ..
The following K line describes the area to be investigated. On the second line of j + M + (1 ≤ j ≤ K), the positive integers aj, bj, cj, and dj representing the jth region are written with blanks as delimiters. (aj, bj) represents the northwest corner section of the survey area, and (cj, dj) represents the southeast corner section of the survey area. However, aj, bj, cj, and dj satisfy 1 ≤ aj ≤ cj ≤ M, 1 ≤ bj ≤ dj ≤ N.
output
Output K lines representing the results of the survey to standard output. Line j of the output contains three integers representing the number of "jungle" (J) compartments, the "sea" (O) compartment, and the "ice" (I) compartment in the jth survey area. , In this order, separated by blanks.
We need to solve: given M x N grid of characters J, O, I, and K queries each specifying a rectangle from (a,b) (top-left) to (c,d) (bottom-right). For each query, count numbers of J, O, I in that rectangle.
Constraints? Not provided. Typically, M,N up to maybe 1000? Or maybe larger (10^5?). Since we need to answer many queries (K up to maybe 10^5). We can compute prefix sums for each character. So we can precompute 2D prefix sums for count of J, O, I. Then each query answer in O(1).
Standard: prefix[i][j] = number of J in rectangle from (1,1) to (i,j). Similarly for O and I. We'll compute three arrays, or one array storing three values.
Given M,N up to maybe 2000? But can be up to 10^3? Actually typical competitive programming problem "JOI" map queries. But we'll implement with 2D prefix sums.
Time complexity: O(M*N + K).
We need to read input carefully. Input format:
First line: M N
Second line: K
Next M lines: strings of length N
Next K lines: a b c d
Constraints: 1 <= a <= c <= M, 1 <= b <= d <= N.
We output for each query: count_J count_O count_I.
We need to watch for indexing. Prefix sums array size (M+1) x (N+1) for convenience.
Implementation in Python.
Pseudo:
read M, N
read K
grid = []
for _ in range(M):
line = input().strip()
grid.append(line)
Initialize prefix arrays of size (M+1)*(N+1) with zeros
prefJ = [[0](N+1) for _ in range(M+1)]
prefO = [[0](N+1) for _ in range(M+1)]
prefI = [[0]*(N+1) for _ in range(M+1)]
for i in range(1, M+1):
row = grid[i-1]
for j in range(1, N+1):
ch = row[j-1]
prefJ[i][j] = prefJ[i-1][j] + prefJ[i][j-1] - prefJ[i-1][j-1] + (1 if ch=='J' else 0)
prefO[i][j] = prefO[i-1][j] + prefO[i][j-1] - prefO[i-1][j-1] + (1 if ch=='O' else 0)
prefI[i][j] = prefI[i-1][j] + prefI[i][j-1] - prefI[i-1][j-1] + (1 if ch=='I' else 0)
outputs = []
for _ in range(K):
a,b,c,d = map(int, input().split())
# rectangle from (a,b) to (c,d) inclusive.
# compute for each char:
def count(pref):
return pref[c][d] - pref[a-1][d] - pref[c][b-1] + pref[a-1][b-1]
j = count(prefJ)
o = count(prefO)
i = count(prefI)
outputs.append(f"{j} {o} {i}")
print each line.
That's it.
Now, we consider memory: M,N maybe up to 1000? Then 3*(M+1)(N+1) ints ~31e6, fine. If M,N up to 3000, 9e6 ints, still okay in Python? Maybe around 9e6 * 28 bytes ~ 252 MB? Might be high. But typical constraints maybe M,N <= 2000, K <= 100000. We can also compress by using a single array of three counts? Or use list of lists of ints.
Alternative: use three separate 2D arrays, or one 2D array storing tuple? But better to use three separate lists.
If M,N up to 2000, 2001*2001 ~4e6; times 3 =12e6 ints. Python ints are heavy (~28 bytes) so ~336 MB, could be memory limit exceed. Possibly constraints are lower. But there might be more efficient representation using arrays from module array or numpy? Probably not needed.
But we can also compute prefix sums in a cumulative way using integer arrays of type 'int' using Python's built-in int, but memory might be high. We can instead store prefix sums as list of lists of ints for each character. However, typical JOI problems (from Japan Olympiad in Informatics) often have M,N up to 1000? Actually JOI 2013/2014? There is a problem "JOI Poster" but not sure.
Alternatively, we can compute prefix sums for all three counts using a single 2D array storing a tuple of three ints? That would still be 3 ints per cell. Or we can store as three separate arrays, but still same number of ints.
Better: use 2D list of small ints? But Python's ints are objects.
But constraints might be up to 2000? Then 320012001 ~12 million ints. That might be borderline but possible if memory limit is high (512 MB). But many Python solutions for similar problems use 2D prefix sum with M,N up to 2000 and succeed.
Alternatively, we could compress by using only one pass and answer queries online? No, we need fast per query.
But wait: K can be up to 10^5. So O(K) is fine.
I'll assume typical constraints are moderate.
We'll implement as described.
Edge Cases: Input may have extra spaces, but we'll use split and strip.
Let's compute manually from example output: 1 3 2.
We'll trust our code.
Implementation details: Use sys.stdin.read() for faster input if needed. But simple input reading with sys.stdin.readline is fine.
We'll write final answer.
But the problem statement seems to have some broken English: "I decided to investigate how many sections of "jungle," "sea," and "ice" are included in the rectangular area at K." Actually K is number of queries.
We'll produce code.
Now, careful: The input says: "The following M line contains information on the planned residence. The second line of i + (1 ≤ i ≤ M) contains ..." It might be mis-numbering. But we just read M lines after K.
Now finalize.
I'll include in final answer a Python solution with prefix sums.
But I'm ChatGPT, must output just the answer? The user said: "After a long journey ..." This is a problem statement and request to provide solution? Possibly they want code? The user is a contestant wanting solution. So I should output the code? The instruction: "Output K lines representing the results of the survey to standard output." But the conversation is about solving the problem. Typically in these scenarios, the assistant provides the solution code. But the user didn't explicitly ask for code; they described the problem. In such interactive problem-solving, I should produce an explanation and the code. However, the final answer should be the solution? Since the platform might be expecting just code? Actually the user didn't specify. Usually, as ChatGPT, I can provide both explanation and code. But final answer should be the code or the output? The problem says "output ...". But that's for the program. Since the user asks "After a long journey...", it's like they want to solve it. I will respond with a Python solution and brief explanation.
Thus final answer: Provide Python code.
But careful: Some problems require specific formatting; but I think just code is fine.
I'll provide a solution that reads from stdin, prints to stdout.
Potential pitfalls: Input size big, so use sys.stdin.buffer for faster reading. We'll parse with split.
We'll use map(int, data) and for strings.
Simplify: Use sys.stdin.read().split() to get tokens. But strings (grid lines) contain characters without spaces; they are entire lines. If we split by whitespace, each grid line will be a token, good.
Let's design using read().splitlines()? Better: tokens = sys.stdin.buffer.read().split() returns list of byte strings. M, N, K are ints. Then M lines each as byte string of length N. Then K*4 ints. However, splitting will treat each grid line as one token (since no spaces). That works. Then we convert accordingly.
But careful: The grid lines might have newline at the end, but split() will strip whitespace, so each line becomes a byte string. That's fine.
Then we can process.
Implementation:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
M = int(next(it))
N = int(next(it))
K = int(next(it))
grid = [next(it).decode() for _ in range(M)] # decode to str; but we could treat as bytes and compare to b'J' etc.
# We'll keep as bytes for speed: grid_bytes = [next(it) for _ in range(M)]
# but easier with decode.
# We'll compute prefix sums.
prefJ = [[0](N+1) for _ in range(M+1)]
prefO = [[0](N+1) for _ in range(M+1)]
prefI = [[0]*(N+1) for _ in range(M+1)]
for i in range(1, M+1):
row = grid[i-1]
sumJ_row = 0
sumO_row = 0
sumI_row = 0
# Use local variables for speed
for j in range(1, N+1):
ch = row[j-1]
if ch == 'J':
vJ = 1
vO = 0
vI = 0
elif ch == 'O':
vJ = 0
vO = 1
vI = 0
else: # 'I'
vJ = 0
vO = 0
vI = 1
prefJ[i][j] = prefJ[i-1][j] + vJ
prefO[i][j] = prefO[i-1][j] + vO
prefI[i][j] = prefI[i-1][j] + vI
# But wait, we need to incorporate left as well. Actually 2D prefix needs both. However we can compute by adding left prefix from same row. However above only adds top. The proper recurrence: pref[i][j] = pref[i-1][j] + pref[i][j-1] - pref[i-1][j-1] + value.
# Could compute row-wise cumulative first then add top? Actually we can compute row by row:
# prefJ[i][j] = prefJ[i][j-1] + prefJ[i-1][j] - prefJ[i-1][j-1] + value.
# So we need to access pref[i][j-1] already computed in same row.
# So we can do inner loop with that recurrence.
# Actually my above loop only used pref[i-1][j]. That's incorrect because we didn't subtract pref[i-1][j-1] and add pref[i][j-1]. So let's correct.
code
for i in range(1, M+1):
row = grid[i-1]
for j in range(1, N+1):
ch = row[j-1]
vJ = 1 if ch=='J' else 0
vO = 1 if ch=='O' else 0
vI = 1 if ch=='I' else 0
prefJ[i][j] = prefJ[i-1][j] + prefJ[i][j-1] - prefJ[i-1][j-1] + vJ
prefO[i][j] = prefO[i-1][j] + prefO[i][j-1] - prefO[i-1][j-1] + vO
prefI[i][j] = prefI[i-1][j] + prefI[i][j-1] - prefI[i-1][j-1] + vI
out_lines = []
for _ in range(K):
a = int(next(it))
b = int(next(it))
c = int(next(it))
d = int(next(it))
j = prefJ[c][d] - prefJ[a-1][d] - prefJ[c][b-1] + prefJ[a-1][b-1]
o = prefO[c][d] - prefO[a-1][d] - prefO[c][b-1] + prefO[a-1][b-1]
i_ = prefI[c][d] - prefI[a-1][d] - prefI[c][b-1] + prefI[a-1][b-1]
out_lines.append(f"{j} {o} {i_}")
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
That's the solution.
But we can further micro-opt: Use bytes and compare to ord('J'), etc., to avoid decode. But not necessary.
Now we need to be careful: In reading data with split, the grid lines may be read as bytes. In that case, row[j-1] is an integer (ASCII code). So we can compare to ord('J') etc. That may be faster and avoid decode. Let's implement that for safety.
Implementation with bytes:
grid_bytes = [next(it) for _ in range(M)] # each is bytes of length N
Then inside loop:
row = grid_bytes[i-1]
for j in range(1, N+1):
ch = row[j-1] # int (0-255)
if ch == 74: # 'J'
vJ=1; vO=0; vI=0
elif ch == 79: # 'O'
vJ=0; vO=1; vI=0
else: # 'I' 73
vJ=0; vO=0; vI=1
But need to ensure row is bytes; indexing yields int in Python3.
Alternatively use a small dictionary or mapping: value = (ch==74, ch==79, ch==73). But conditions fine.
Now we still compute prefix sums.
Now about memory: Use three lists of lists. Could also use list comprehension with [0] * (N+1) for each row, but careful: [ [0]*(N+1) for _ in range(M+1) ] is fine.
Now handle large M,N with memory: maybe we can store prefix sums for each char in a single list of lists of length 3? But not necessary.
But I recall that typical Japanese problems have M,N up to 2000 and K up to 200000; Python solution with prefix sums passes if optimized.
But we can also use a single 2D array storing counts as tuple? Not better.
Alternatively, we can compute prefix sums for each character using separate arrays of type 'int' from module array? But more complex.
We'll stick to simple.
Potential pitfalls: Input may have trailing spaces, but split handles.