AcWing 798. 差分矩阵
原题链接
简单
作者:
楚有养由基者
,
2021-04-21 18:59:40
,
所有人可见
,
阅读 249
二维差分
分析过程(建议画图辅助理解):
1. 找核心操作
- 通过分析题目,将a[x1][y1]到a[x2][y2]表示的矩阵内的元素全部加上c,其核心操作为:
- b[x1][y1] += c;
- b[x2 + 1][y1] -= c;
- b[x1][y2 + 1] -= c;
- b[x2 + 1][y2 + 1] += c;
2. 求差分矩阵
- 同理,将上面的[x1][y1]到[x2][y2]全部加上c看做是[i][j]到[i][j]全部加上a[i][j],则可求出b[i][j]:
- b[i][j] += a[i][j]
- b[i][j + 1] -= a[i][j];
- b[i + 1][j] -= a[i][j];
- b[i + 1][j + 1] += a[i][j];
3. 修改差分矩阵
4. 求前缀和得到答案,即矩阵a
- 求上一步修改过后的差分矩阵b的二维前缀和:
a[i][j] = a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1] + b[i][j];
总结
- 求解此问题第1步找核心操作,第二步求出差分矩阵,然后通过对差分矩阵进行操作来达到自己的目的。
C++代码
#include<iostream>
using namespace std;
const int N = 1010;
int a[N][N], b[N][N];
int n, m, q;
void insert(int x1, int y1, int x2, int y2, int c)
{
b[x1][y1] += c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y1] -= 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 - 1][j] + a[i][j - 1] - 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;
}