Detailed explanation of two-dimensional difference

Foreword
In the last issue, we shared how to use one-dimensional difference. In this issue, we will continue the content of the previous issue to show you how to use two-dimensional difference. Not much to say. Say, LET'S GO! (Previous issue link)
Insert image description here

Two-dimensional difference
Two-dimensional difference can be used to perform multiple operations on matrix intervals.
For two-dimensional difference, we can also use the idea of ​​one-dimensional difference, as shown in the figure. If we want to add 1 to the elements of the interval [x1, x2], [y1, y2]:
Insert image description here
i.e.:

        arrsum[x1][y1] += 1;
		arrsum[x1][y2+1] -= 1;
		arrsum[x2+1	][y1] -= 1;
		arrsum[x2+1][y2+1] += 1;

The idea is like this. After the operation, directly find the complete conjugation of the array to be the target matrix array. Let's go to the actual combat.
Given the matrix array arr, there are n rows and m columns. Perform t operations on it. Each operation will add 1 to the elements in the interval [x1, x2], [y1,y2]. , please output the arr array after the operation.
Input sample
The first row contains n, m and q
The next n rows are elements of the matrix array
The future q behavior is x1, y1, x2, y2
Test example
3 3 2
1 1 1
1 1 1
1 1 1
1 1 2 2
2 2 3 3
Output sample
2 2 1
2 3 2
1 2 2
Solution:

#include<stdio.h>
int arr[100][100];
int arrsum[100][100];//前缀和数组
int main()
{
    
    
	int n, m, t;
	scanf("%d %d %d", &n, &m, &t);
	for (int i = 1; i <= n; i++)//输入数组
	{
    
    
		for (int j = 1; j <= m; j++)
		{
    
    
			scanf("%d", &arr[i][j]);
		}
	}
	for (int i = 1; i <= n; i++)//操作arrsum数组使其前缀和为目标数组
	{
    
    
		for (int j = 1; j <= m; j++)
		{
    
    
			arrsum[i][j] += arr[i][j];
			arrsum[i+1][j] -= arr[i][j];
			arrsum[i][j+1] -= arr[i][j];
			arrsum[i+1][j+1] += arr[i][j];
		}
	}
	while (t--)//t次操作
	{
    
    
		int x1, y1, x2, y2;
		scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
		arrsum[x1][y1] += 1;
		arrsum[x1][y2+1] -= 1;
		arrsum[x2+1	][y1] -= 1;
		arrsum[x2+1][y2+1] += 1;
	}
	for (int i = 1; i <= n; i++)//求前缀和
	{
    
    
		for (int j = 1; j <= m; j++)
		{
    
    
			arrsum[i][j] += arrsum[i-1][j]+arrsum[i][j-1]-arrsum[i-1][j-1];	
		}
	}
	for (int i = 1; i <= n; i++)//打印目标数组
	{
    
    
		for (int j = 1; j <= m; j++)
		{
    
    
			printf("%d ", arrsum[i][j]);
		}
		printf("\n");
	}
	return 0;
}

Epilogue
That’s it for this sharing. If you think the blogger’s words are good, please give the blogger a follow, like, favorite and support~, the blogger will continue to do so Share more knowledge and see you next time!

Guess you like

Origin blog.csdn.net/Tokai___Teio/article/details/135031113