差分的定义:首先我们有一个原数组a[n]与一个差分数组b[n],原数组a[i] = b[1]+b[2]+...+b[n]
一维差分:
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int a[N],b[N];//a为原数组,b为差分数组
int n,m;
void insert(int l,int r,int c)//要想在使原数组[l,r]区间的数全加c,就得在差分数组b[l]+=c、b[r+1]-=c,最后求前缀和即可
{
b[l] += c;
b[r + 1] -= c;
}
int main ()
{
scanf ("%d%d",&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]); //初始化差分数组b[n]
while (m--)
{
int l,r,c;
scanf ("%d%d%d",&l,&r,&c);
insert(l,r,c);
}
for (int i = 1;i <= n;i++) b[i] += b[i - 1];
for (int i = 1;i &l