题目:
思路:类似一维的前缀和
求和公式:arr[i][j]=a[i][j]+arr[i-1][j]+arr[i][j-1]-arr[i-1][j-1];
求区间和:arr[xx][yy]-arr[xx][y-1]-arr[x-1][yy]+arr[x-1][y-1]
AC代码:
package 练习;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
int n=scanner.nextInt();
int m=scanner.nextInt();
int t=scanner.nextInt();
int a[][]=new int [n+1][m+1];
int arr[][]=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();
}
}
for(int i=1;i<=n;i++) {//前缀求和
for(int j=1;j<=m;j++) {
arr[i][j]=a[i][j]+arr[i-1][j]+arr[i][j-1]-arr[i-1][j-1];
}
}
// for(int i=0;i<=n;i++) {
// System.out.println(Arrays.toString(arr[i]));
// }
for(int i=0;i<t;i++) {
int x=scanner.nextInt();
int y=scanner.nextInt();
int xx=scanner.nextInt();
int yy=scanner.nextInt();
System.out.println(arr[xx][yy]-arr[xx][y-1]-arr[x-1][yy]+arr[x-1][y-1]);
}
}
}