题目
差分
算法核心
差分数组b[]
,需要记住的是b[]
就相当于是一个增量。
- 边界:
a[0] = b[0]
- 普适公式:
b[i] = a[i] - a[i - 1]
或者是a[i] = a[i - 1] + b[i]
。
代码
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int a[N], b[N];
int l, r, c;
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ ) cin >> a[i];
b[0] = a[0];
for (int i = 1; i < n; i ++ )
b[i] = a[i] - a[i - 1];
while (m --)
{
cin >> l >> r >> c;
b[l - 1] += c;
b[r] -= c;
}
a[0] = b[0];
for (int i = 1; i < n; i ++ )
a[i] = a[i - 1] + b[i];
for (int i = 0; i < n; i ++ )
cout << a[i] << ' ';
cout << endl;
return 0;
}