题解 | #【模板】前缀和#
【模板】前缀和
https://www.nowcoder.com/practice/acead2f4c28c401889915da98ecdc6bf?tpId=230&&tqId=38960&sourceUrl=https%3A%2F%2Fwww.nowcoder.com%2Fexam%2Foj
#include <iostream> #include <vector> using namespace std; int main() { int n,q; int l,r; cin >> n >> q; vector<int> arr(n+1); vector<long long> dp(n+1);//防止溢出 for(int i = 1; i <= n; i++) { cin >> arr[i]; //构造前缀和数组 dp[i] = dp[i-1] + arr[i]; } //使用前缀和数组 while(q--) { cin >> l >> r; cout << dp[r] - dp[l-1] << endl; } }