二维差分--矩阵修改

方法一:二维数组化为一维数组

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int N = 1e7;
int num[N] = { 0 };
int diff[N] = { 0 };

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int n, m, q;
	cin >> n >> m >> q;//输入行数列数与修改的次数
	
	int sum = n * m;

	//仅记录行数与列数,将二维数组化为一维数组
	for (int i = 1; i <= sum; i++) {
		cin >> num[i];
	}

	//维护差分数组
	for (int i = 1; i <= sum; i++) {
		diff[i] = num[i] - num[i - 1];
	}

	//q次修改
	while (q--) {
		int x1, y1, x2, y2, c;
		cin >> x1 >> y1 >> x2 >> y2 >> c;
		int temp = x2 - x1 + 1;
		while (temp--) {
			int l = m * (x1 - 1 + temp) + y1;//x2自减,一直减到x1为止,当前行的left区间
			int r = l + (y2 - y1);//当前行的right区间
			
			diff[l] += c;//修改区间值
			diff[r + 1] -= c;
		}
	}

	//差分数组前缀和还原为原数组
	for (int i = 1; i <= sum; i++) {
		diff[i] += diff[i - 1];
		cout << diff[i] << " \n"[i % m == 0];//以二维数组形式输出
	}

	return 0;
}

方法二:二维差分数组

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e3 + 6;
const int MAXM = 1e3 + 6;
int a[MAXN][MAXM] = { 0 };
int diff[MAXN][MAXM] = { 0 };

int main() {
    int n, m, q;
    cin >> n >> m >> q;

    int i, j;
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= m; j++) {
            cin >> a[i][j];
            //二维前缀和表示的是右上角矩形的和,可推出二维差分公式
            diff[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1];
        }
    }

    //二维diff数组维护
    for (i = 0; i < q; i++) {
        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 (i = 1; i <= n; i++) {
        for (j = 1; j <= m; j++) {
            diff[i][j] += diff[i - 1][j] + diff[i][j - 1] - diff[i - 1][j - 1];
            cout << diff[i][j] << " \n"[j == m];
        }
    }

    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值