解题思路
样例
1 7 2 4
3 6 2 8
2 1 2 3
求任意子矩阵的和
二维前缀和公式
相关代码
import java.util.Scanner;
public class Main {
public static void main(String[] args){
//二维子矩阵的元素和
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int q = scanner.nextInt();
int a[][] = new int[n+1][m+1];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
a[i][j] = scanner.nextInt();
//进行前缀和预处理
int s[][] = new int[n+1][m+1];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
s[i][j]=s[i][j-1]+s[i-1][j]-s[i-1][j-1]+a[i][j];
while(q-->0){
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
System.out.println(s[x2][y2]-s[x2][y1-1]-s[x1-1][y2]+s[x1-1][y1-1]);
}
}
}