文章目录
- 一维差分
- 二维差分
一维差分
#include
using namespace std;
const int N = 1e5 + 10;
int s[N], a[N];
void insert(int l, int r, int x){
a[l] += x;
a[r + 1] -= x;
}
int main(){
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i ++){cin >> s[i];insert(i, i, s[i]);
} while(m --){int l, r, c;cin >> l >> r >> c;insert(l, r, c);
}for (int i = 1; i <= n; i ++){s[i] = a[i] + s[i - 1];cout << s[i] << ' ';
}
}
二维差分
#include <iostream>using namespace std;
const int N = 1010;
int s[N][N], a[N][N];void insert(int x1, int y1, int x2, int y2, int x){a[x1][y1] += x;a[x2+1][y1] -= x;a[x1][y2+1] -= x;a[x2+1][y2+1] += x;
}
int main(){int n, m, q;cin >> n >> m >> q;for (int i = 1; i <= n; i ++){for (int j = 1; j <= m; j ++){cin >> s[i][j];insert(i,j,i,j,s[i][j]);}}while(q --){int x1, y1, x2, y2, x;cin >> x1 >> y1 >> x2 >> y2 >> x;insert(x1, y1, x2, y2, x);}for (int i = 1; i <= n; i ++){for(int j = 1; j <= m; j ++){s[i][j] = a[i][j] + s[i-1][j] + s[i][j-1] - s[i-1][j-1];cout << s[i][j] << ' ';}cout << endl;}return 0;
}