Difference matrix

Title description

Enter an integer matrix of n rows and m columns, and then enter q operations, each operation contains five integers x1, y1, x2, y2, c, where (x1, y1) and (x2, y2) represent the The coordinates of the upper left corner and the coordinates of the lower right corner.

Each operation adds c to the value of each element in the selected sub-matrix.

Please output the matrix after all operations

Input format

The first line contains integers n, m, q.

The next n rows, each row contains m integers, represent an integer matrix.

The next q lines, each line contains 5 integers x1, y1, x2, y2, c, representing an operation.

data range

1≤n, m≤1000,
1≤q≤100000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤c≤1000,
−1000≤values ​​of elements in the matrix ≤1000

Sample input:

3 4 3
1 2 2 1
3 2 2 1
1 1 1 1
1 1 2 2 1
1 3 2 3 2
3 1 3 4 1

Sample output:

2 3 4 1
4 3 4 1
2 2 2 2

Problem-solving ideas

Differential initialization,

Assuming that the elements of the a array are 0
, for each element of the a array, [i, j] performs a difference

Differential process

Insert picture description here

b[x1][y1] += c
b[x2+1][y1] -=c
b[x1][y2+1] -=c
b[x2+1][y2+1] +=c

Code

#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[x2+1][y1] -=c;
    b[x1][y2+1] -=c;
    b[x2+1][y2+1] +=c;
}
int main()
{
    scanf("%d%d%d",&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;
        scanf("%d%d%d%d%d",&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;
}
Published 253 original articles · praised 41 · 40,000+ views

Guess you like

Origin blog.csdn.net/liuyuchen282828/article/details/105655279