【二维差分】 差分矩阵
传送门
题意
给定一个\(n\times m\)的初始矩阵,\(q\)个操作,每个操作包含\(x_{1},y_{1},x_{2},y_{2},c\),使\((x1, y1)\)为左上角,\((x2, y2)\)为右下角的子矩阵中的所有元素加上\(c\)
求所有操作后的矩阵
数据范围
\(\begin{array}{l}1 \leq n, m \leq 1000 \\ 1 \leq q \leq 100000 \\ 1 \leq x 1 \leq x 2 \leq n \\ 1 \leq y 1 \leq y 2 \leq m \\ -1000 \leq c \leq 1000 \\ -1000 \leq \text { 矩阵内元素的值 } \leq 1000\end{array}\)
题解
\(S[x1, y1] \:+= c\)
\(S[x2 + 1, y1] \:-= c\)
\(S[x1, y2 + 1] \:-= c\)
\(S[x2 + 1, y2 + 1] \:+= c\)
Code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e3+10;
int a[N][N],b[N][N];
int n,m,q;
inline void insert(int x1,int y1,int x2,int y2,int c){
b[x1][y1]+= c;
b[x2+1][y1]-=c;
b[x1][y2+1]-=c;
b[x2+1][y2+1]+=c;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>m>>q;
b[0][0]=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>a[i][j];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
insert(i,j,i,j,a[i][j]);
while(q--){
int x1,y1,x2,y2,c;
cin>>x1>>y1>>x2>>y2>>c;
insert(x1,y1,x2,y2,c);
}
for(int i=1;i<=n;i++) {
for (int j = 1; j <= m; j++) {
b[i][j] = b[i][j] + b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
cout << b[i][j] << ' ';
}
cout<<endl;
}
}

浙公网安备 33010602011771号