前缀和的逆运算:
给定a[1],a[2],a[3],…a[n],构造差分数组b[n],使得
a[i] = b[1] + b[2] + … + b[i]
作用:当需要给序列的区间L-R内的数均加上或者减去某个数,操作简单
给L-R区间加上C:b[L] += C, b[R + 1] -= C;
通过这个特性,同样可以用这个方法来构造差分数组;
§ 初始时设置b差分数组为0
§ 然后给每个区间为1的区间进行操作即可
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1E5 + 10;
int a[N], b[N];
int n, m;
void insert(int l, int r, int c){
b[l] += c, b[r + 1] -= c;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
for(int i = 1; i <= n; i ++ ) insert(i, i, a[i]);
while(m -- ){
int l, r, c; scanf("%d%d%d", &l, &r, &c);
insert(l, r, c);
}
memset(a, 0, sizeof a);
for(int i = 1; i <= n; i ++ ) a[i] += a[i - 1] + b[i];
for(int i = 1; i <= n; i ++ ) printf("%d ", a[i]);
return 0;
}