前缀和 & 差分
参考资料
前缀和
前缀和可以简单理解为「数列的前 项的和」,是一种重要的预处理方式,能大大降低查询的时间复杂度。
差分
差分是一种和前缀和相对的策略,可以当做是求和的逆运算。
STL
例题
洛谷 P8218 【深进1.例1】求区间和
给定由 个正整数组成的序列 和 个区间 ,分别求这 个区间的区间和。
代码(1)
#include <bits/stdc++.h>
using namespace std;
const int N=100005;
int a[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
a[i]+=a[i-1];
}
int m;
cin>>m;
while(m--)
{
int l,r;
cin>>l>>r;
cout<<a[r]-a[l-1]<<'\n';
}
return 0;
}