一.一维前缀和
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 长度为n
int q = sc.nextInt(); // 查询q次
int[] arr = new int[n + 1];
long[] dp = new long[n + 1]; // 防止溢出
for (int i = 1; i <= n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++) {
dp[i] = dp[i - 1] + arr[i];
}
while (q > 0) { //为0时查询结束
int l = sc.nextInt();
int r = sc.nextInt();
System.out.println(dp[r] - dp[l - 1]);
q--;
}
}
}
二.二维前缀和
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // n行
int m = sc.nextInt(); // m列
int q = sc.nextInt(); // 查询q次
int[][] array = new int[n + 1][m + 1];
long[][] dp = new long[n + 1][m + 1]; // 防止溢出
// 读入数据
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
array[i][j] = sc.nextInt();
}
}
// 处理前缀和矩阵
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + array[i][j];
}
}
// 使用前缀矩阵
while (q > 0) {
int x1 = sc.nextInt(), y1 = sc.nextInt();
int x2 = sc.nextInt(), y2 = sc.nextInt();
long ret = dp[x2][y2] - dp[x1 - 1][y2] - dp[x2][y1 - 1] + dp[x1 - 1][y1 - 1];
System.out.println(ret);
q--;
}
}
}