差分是前缀和的逆运算
一维数组 $diff[i]$ 记录了 $a[i]-a[i-1]$
对于区间$[l,r]$同时加$w$
$Diff[1]+=w$
看一道例题:
Code:
#include<iostream>
using namespace std;
const int N = 1e7 + 10;
int q[N], s[N];
void insert( int l , int r , int c ){
s[l] += c;
s[ r + 1] -= c;
}
int main(){
int n , m ;
cin>> n >> m;
for( int i = 1 ; i <= n ; i++ ){
cin >>q[i];
insert( i , i , q[i] );
}
while( m-- ){
int l , r , c;
scanf("%d%d%d" , &l , &r , &c);
insert( l , r , c );
}
for( int i = 1 ; i <= n ; i++ ) s[i] += s[i - 1]; //差分后进行累加
for( int i = 1 ; i <= n ; i++ ) cout<<s[i]<<" ";
}
标签:insert,int,d%,差分,逆运算,例题
From: https://www.cnblogs.com/2509-SYM/p/17574706.html