差分简介
原数组
a[1], a[2], a[3], a[4], ..., a[n]
构造
b[1], b[2], b[3], b[4], ..., b[n]
使得
a[i] = b[1] + b[2] + ... + b[i]
把a数组中 区间为 [l, r]中每个数据都加 C 用暴力需要O(n)
用差分只需要O(1)
只需要 b[l] + C , b[r + 1] - C
其实反过来说 a数组为b数组的前缀和
代码
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int n, m;
int a[N], b[N];
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 ++) cin >> a[i];
for (int j = 1; j <= n; j ++) insert(j, j, a[j]);
while (m --)
{
int l, r, c;
cin >> l >> r >> c;
insert (l, r, c);
}
for (int i = 1; i <= n; i ++) b[i] += b[i -1];
for (int i = 1; i <= n; i ++) cout << b[i] << ' ';
system("pause");
return 0;
}