题解 | #【模板】二维前缀和#
【模板】二维前缀和
https://www.nowcoder.com/practice/99eb8040d116414ea3296467ce81cbbc
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i == 0 && j == 0) { arr[i][j] = in.nextLong(); } else if (i == 0) { arr[i][j] = in.nextLong() + arr[i][j-1]; } else if (j == 0) { arr[i][j] = in.nextLong() + arr[i-1][j]; } else { arr[i][j] = in.nextLong() - arr[i-1][j-1] + arr[i-1][j] + arr[i][j-1]; } } } for (int i = 0; i < q; i++) { int x1 = in.nextInt()-1; int y1 = in.nextInt()-1; int x2 = in.nextInt()-1; int y2 = in.nextInt()-1; if (x1 == 0 && y1 == 0) { System.out.println(arr[x2][y2]); } else if (x1 == 0) { System.out.println(arr[x2][y2]-arr[x2][y1-1]); } else if (y1 == 0) { System.out.println(arr[x2][y2]-arr[x1-1][y2]); } else { System.out.println(arr[x2][y2]-arr[x2][y1-1]-arr[x1-1][y2]+arr[x1-1][y1-1]); } } } }