解题思路:

  • 直接存储前n项的和。对于查询q[l to r]=sum[0 to r]sum[0 to l1]q_{[l\ to\ r]} = sum_{[0\ to\ r]} - sum_{[0\ to\ l-1]},时间复杂度O(n+q),空间复杂度O(n)
#include<bits/stdc++.h>
using namespace std;
int main(){
    int n, q;
    cin>>n>>q;
    vector<long long>v(n+1);
    long long  sum = 0;
    for(int i = 1; i <= n; ++i){
        scanf("%lld", &v[i]);
        sum += v[i];
        v[i] = sum;
    }
    for(int i = 0; i < q; ++i){
        int start, end;
        cin>>start>>end;
        cout<<v[end] - (start == 1? 0: v[start-1])<<endl;
    }
    return 0;
}