题目描述
差分矩阵
模板分六步
1、先写出 insert() 函数 ;
2、读取数据 a[ ] ;
3、计算差分 d[ ] ;
4、调 insert() 函数 +c ;
5、求前缀和 ;
6、遍历输出 ;
#include <iostream>
using namespace std;
#define int long long
const int N = 1010;
int a[N][N], d[N][N];
void insert(int x1, int y1, int x2, int y2, int c)
{
d[x1][y1] += c;
d[x1][y2+1] -= c;
d[x2+1][y1] -= c;
d[x2+1][y2+1] += c;
}
signed main()
{
int n, m, q;
cin >> n >> m >> q;
// 先读取
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
scanf("%lld", &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;
scanf("%lld%lld%lld%lld%lld",&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 ++ )
d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1];
// 遍历输出
for (int i = 1; i <= n; i ++ )
{
for (int j = 1; j <= m; j ++ ) printf("%lld ", d[i][j]);
printf("\n");
}
return 0;
}