二维差分

原理

模板题

AcWing-798-差分矩阵open in new window

#include <iostream>
using namespace std;

const int N = 1010;
int a[N][N], d[N][N];

void modify (int x1, int y1, int x2, int y2, int val) {
    d[x1][y1] += val;
    d[x2 + 1][y1] -= val;
    d[x1][y2 + 1] -= val;
    d[x2 + 1][y2 + 1] += val;
}

int main () {
    int n, m, q;
    scanf("%d%d%d", &n, &m, &q);
    for (int i = 1; i <= n; ++ i) {
        for (int j = 1; j <= m; ++ j) {
            scanf("%d", &a[i][j]);
            modify(i, j, i, j, a[i][j]);
        }
    }

    while (q --) {
        int x1, y1, x2, y2, val;
        scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &val);
        modify(x1, y1, x2, y2, val);
    }

    for (int i = 1; i <= n; ++ i)
        for (int j = 1; j <= m; ++ j)
            d[i][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("%d ", d[i][j]);
        }
        printf("\n");
    }
    return 0;
}
最后修改于: