c++一般思路,为了便于理解同样采用双数组 原数组和差分数组
#include<iostream>
using namespace std;
constexpr int N = 1e+3 + 10;
int n,m,q; // n行m列的矩阵 , q为后面进行的操作次数
int a[N][N], b[N][N]; // a为原数组 b为差分数组
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()
{
cin >> n >> m >> q;
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) a[i][j] = a[i][j-1] + a[i-1][j] - a[i-1][j-1] + b[i][j]; //求子矩阵的和
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= m; ++j)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
插入操作为啥这样写
更简洁的代码
#include<iostream>
using namespace std;
constexpr int N = 1e+3 + 10;
int n,m,q;
int a[N][N];
void insert(int x1, int y1, int x2, int y2, int c)
{
a[x1][y1] += c;
a[x2 + 1][y1] -= c;
a[x1][y2 + 1] -= c;
a[x2+1][y2+1] += c;
}
int main()
{
cin >> n >> m >> q;
int d;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j) cin >> d, insert(i,j,i,j,d);
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) a[i][j] += a[i][j-1] + a[i-1][j] - a[i-1][j-1];
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= m; ++j)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}