菜鸟的博客

纵有疾风起,人生不言弃。

导航

前缀和

//求某个数组某一段的和
//s[i] = s[i-1]+a[i];
//同理:正方形矩阵求S[i,j]:S[i,j] = S[i-1,j]+S[i,j-1]-S[i-1,j-1]+a[i,j]
//求子矩阵的和s[x2,y2]-s[x2,y1-1]-s[x1-1,y2]-s[x1-1,y1-1];
import java.util.Scanner;

public class Main{
    static final int N = 100010;
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        int a[] = new int[N];
        int s[] = new int[N];
        s[0] = 0;
        for(int i = 1;i<=m;i++){
            a[i] = scanner.nextInt();
        }
        for(int i = 1;i<=m;i++){
            s[i] = s[i-1]+a[i];
        }
        while(n!=0){
            n--;
            int l = scanner.nextInt();
            int r = scanner.nextInt();
            System.out.println(s[r]-s[l-1]);
        }
        scanner.close();
    }
}

 

posted on 2023-12-21 22:17  hhmzd233  阅读(3)  评论(0编辑  收藏  举报