1.前缀和
import java.util.Scanner;
public class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(),q = sc.nextInt();
int []a = new int[100010];
int []b = new int[100010];
for(int i=1;i<=n;i++){
a[i] = sc.nextInt();
b[i]=b[i-1]+a[i];
}
while(q-->0){
int l = sc.nextInt(),r = sc.nextInt();
System.out.println(b[r]-b[l-1]);
}
}
}
2.二维前缀和
import java.util.Scanner;
public class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(),m = sc.nextInt(),q = sc.nextInt();
int [][]a = new int[n+1][m+1];
int [][]s = new int[n+1][m+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
a[i][j] = sc.nextInt();
s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1]+a[i][j];
}
}
while(q-->0){
int x1 = sc.nextInt(),y1 = sc.nextInt(),x2 = sc.nextInt(),y2 = sc.nextInt();
System.out.println(s[x2][y2]-s[x1-1][y2]-s[x2][y1-1]+s[x1-1][y1-1]);
}
}
}