题解 | #【模板】前缀和#
【模板】前缀和
http://www.nowcoder.com/practice/acead2f4c28c401889915da98ecdc6bf
动态规划(C++)
核心是这个:
下标从 1 开始
S[i] = a[1] + a[2] + ... a[i]
a[l] + ... + a[r] = S[r] - S[l - 1]
#include <iostream>
using namespace std;
const int N = 1e5 + 5;
int n, q;
int a[N];
long long s[N];
int main() {
cin >> n >> q;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) s[i] = a[i] + s[i - 1];
while (q --) {
int l, r;
cin >> l >> r;
cout << s[r] - s[l - 1] << endl;
}
return 0;
}