题目:链接
题意
题目意思很简单,就是给定一个矩阵,在其子矩阵上加上相同的数,考点就是二维差分。
思路
二维差分:这些公式一定要记住
diff[i][j] = a[i][j] - a[i][j-1] - a[i-1][j] + a[i - 1][j - 1];
diff[x1][y1] += c;
diff[x1][y2 + 1] -= c;
diff[x2 + 1][y1] -= c;
diff[x2 + 1][y2 + 1] += c;
心得
一开始做的时候,感觉和一维差分没有区别,只要在四个角上做好标记就可以了,但是如果按照每行一维差分,那么行与行之间的联系就被割断了,如果按照每列一维差分,那么列与列之间的联系就被割断了。
代码
#include <bits/stdc++.h>
using namespace std;
int n, m, q;
const int N = 1e3 + 10;
int a[N][N], diff[N][N];
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++)
diff[i][j] = a[i][j] - a[i][j-1] - a[i-1][j] + a[i - 1][j - 1];
while(q--)
{
int x1, y1, x2, y2, c;
cin>>x1>>y1>>x2>>y2>>c;
diff[x1][y1] += c;
diff[x1][y2 + 1] -= c;
diff[x2 + 1][y1] -= c;
diff[x2 + 1][y2 + 1] += c;
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
a[i][j] = diff[i][j] + a[i][j-1] + a[i-1][j] - a[i - 1][j - 1];
cout<<a[i][j]<<' ';
}
cout<<'\n';
}
return 0;
}