输入样例:
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[i][j]数组保存每个从a[1][1]到a[i][j]的子矩阵,查询时只需要O(1)的复杂度即可。
Java代码:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
int q = Integer.parseInt(split[2]);
int [][]arr = new int[n + 1][m + 1];
int [][]s = new int[n + 1][m + 1];
for (int i = 0; i < n; i++) {
split = br.readLine().split(" ");
for(int j = 0; j < split.length; j++) {
arr[i + 1][j + 1] = Integer.parseInt(split[j]);
}
}
for(int i = 1; i <= n; i++) {//处理s数组
for(int j = 1; j <= m; j++) {
s[i][j] = s[i -1][j] + s[i][j - 1] - s[i - 1][j - 1] + arr[i][j];
}
}
for(int i = 0; i < q; i++) {
split = br.readLine().split(" ");
int x1 = Integer.parseInt(split[0]);
int y1 = Integer.parseInt(split[1]);
int x2 = Integer.parseInt(split[2]);
int y2 = Integer.parseInt(split[3]);
System.out.println(s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
}
}
}