一维差分算法核心:给[l,r]区间的每个数+c:b[l]+=c; b[r+1]-=c;
例题:
AC模板:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+10;
int n,m;
int a[N],b[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin>>a[i];
b[i]=a[i]-a[i-1]; //构造差分数组
}
int l,r,c;
while (m -- )
{
cin >> l>>r>>c; //将序列中每个数+c(核心!!关键)
b[l] += c;
b[r+1] -=c;
}
for (int i = 1; i <= n; i ++ )
{
a[i]=b[i]+a[i-1]; //前缀和的计算
cout << a[i] <<" ";
}
return 0;
}