using
System;
public
class
GFG{
static
void
preProcess(
int
[,] mat,
int
[,] dp,
int
n,
int
m)
{
for
(
int
i = 0; i < m; i++) {
dp[0,i] = mat[0,i];
}
for
(
int
i = 1; i < n; i++) {
for
(
int
j = 0; j < m; j++) {
dp[i,j] = dp[i - 1,j] + mat[i,j];
}
}
for
(
int
i = 0; i < n; i++) {
for
(
int
j = 1; j < m; j++) {
dp[i,j] += dp[i,j - 1];
}
}
}
static
int
sumQuery(
int
[,] dp,
int
tli,
int
tlj,
int
rbi,
int
rbj)
{
int
res = dp[rbi,rbj];
if
(tli > 0)
res = res - dp[tli - 1,rbj];
if
(tlj > 0)
res = res - dp[rbi,tlj - 1];
if
(tli > 0 && tlj > 0)
res
= res + dp[tli - 1,tlj - 1];
return
res;
}
static
int
[] maxSubMatrixSumQueries(
int
[,] mat,
int
n,
int
m,
int
[,] queries,
int
q)
{
int
[,] dp =
new
int
[n,m];
preProcess(mat, dp, n, m);
int
[] maxSum =
new
int
[queries.GetLength(0)];
for
(
int
qi = 0; qi < q; qi++) {
for
(
int
i = 0; i < n - queries[qi,0] + 1; i++) {
for
(
int
j = 0; j < m - queries[qi,1] + 1; j++) {
maxSum[qi]
= Math.Max(maxSum[qi],
sumQuery(dp, i, j,
i + queries[qi,0] - 1,
j + queries[qi,1] - 1));
}
}
}
return
maxSum;
}
static
public
void
Main (){
int
n = 3, m = 4;
int
[,] mat = { { 1, 2, 3, 9 },
{ 4, 5, 6, 2 },
{ 8, 3, 2, 6 } };
int
Q = 3;
int
[,] Queries = { { 1, 1 },
{ 2, 2 },
{ 3, 3 } };
int
[] maxSum
= maxSubMatrixSumQueries(
mat, n, m, Queries, Q);
for
(
int
i = 0; i < Q; i++) {
Console.Write(maxSum[i] +
" "
);
}
}
}