解题思路:
- 直接存储前n项的和。对于查询,时间复杂度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;
}