首先需要理解前缀和:前缀和讲解
输入一个 n 行 m 列的整数矩阵,再输入 q 个询问,每个询问包含四个整数 x1,y1,x2,y2,表示一个子矩阵的左上角坐标和右下角坐标。
对于每个询问输出子矩阵中所有数的和。
输入格式
第一行包含三个整数 n,m,q。
接下来 n 行,每行包含 m 个整数,表示整数矩阵。
接下来 q 行,每行包含四个整数 x1,y1,x2,y2,表示一组询问。
输出格式
共 q 行,每行输出一个询问的结果。
数据范围
1≤n,m≤1000,
1≤q≤200000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤矩阵内元素的值≤1000
输入样例:
3 4 3
1 7 2 4
3 6 2 8
2 1 2 3
1 1 2 2
2 1 3 4
1 3 3 4
输出样例:
17
27
21
原理讲解:
如图可知
绿色矩形的面积 = 整个外围面积s[x2, y2]
- 黄色面积s[x2, y1 - 1]
- 紫色面积s[x1 - 1, y2]
+ 重复减去的红色面积 s[x1 - 1, y1 - 1]
所以有
以(x1, y1)
为左上角,(x2, y2)
为右下角的子矩阵的和为:
s[x2, y2] - s[x1 - 1, y2] - s[x2, y1 - 1] + s[x1 - 1, y1 - 1]
提交代码:
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String [] strs = reader.readLine().trim().split(" ");
int n = Integer.parseInt(strs[0]);
int m = Integer.parseInt(strs[1]);
int q = Integer.parseInt(strs[2]);
int a [][] = new int [n + 10][m + 10];
for (int i = 1; i <= n; ++ i)
{
strs = reader.readLine().trim().split(" ");
for (int j = 1; j <= m; ++ j)
{
a[i][j] = Integer.parseInt(strs[j - 1]);
}
}
int sum [][] = new int [n + 10][m + 10];
for (int i = 1; i <= n; ++ i)
{
for (int j = 1; j <= m; ++ j)
{
sum[i][j] = sum[i - 1][j] + a[i][j] + sum[i][j - 1] - sum[i - 1][j - 1];
}
}
while(q -- > 0)
{
strs = reader.readLine().trim().split(" ");
int x1 = Integer.parseInt(strs[0]);
int y1 = Integer.parseInt(strs[1]);
int x2 = Integer.parseInt(strs[2]);
int y2 = Integer.parseInt(strs[3]);
System.out.println(sum[x2][y2] + sum[x1 - 1][y1 - 1] - sum[x2][y1 - 1] - sum[x1 - 1 ][y2]);
}
}
}