题目描述
输入一个n行m列的整数矩阵,再输入q个操作,每个操作包含五个整数x1, y1, x2, y2, c,其中(x1, y1)和(x2, y2)表示一个子矩阵的左上角坐标和右下角坐标。
每个操作都要将选中的子矩阵中的每个元素的值加上c。
请你将进行完所有操作后的矩阵输出。
输入格式
第一行包含整数n,m,q。
接下来n行,每行包含m个整数,表示整数矩阵。
接下来q行,每行包含5个整数x1, y1, x2, y2, c,表示一个操作。
输出格式
共 n 行,每行 m 个整数,表示所有操作进行完毕后的最终矩阵。
数据范围
1≤n,m≤1000,
1≤q≤100000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤c≤1000,
−1000≤矩阵内元素的值≤1000
输入样例:
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
输出样例:
2 3 4 1
4 3 4 1
2 2 2 2
思路
二维差分:注意几个点
a[][]是b[][]的前缀和数组,b是a的差分数组
初始时可以看成a,b数组均为零,然后a的值读入时,看成对[i,j]到[i,j]区间增加a的值来初始化b数组。
这时要增加a中某个区间的值,只需要按该区间操作插入该值即可。
b[x1][y1] += c;
b[x1][y2+1] -= c;
b[x2+1][y1] -= c;
b[x2+1][y2+1] += c;
Java代码
import java.util.Scanner;
public class Main {
static int n;
static int m;
static int q;
static int[][] a;
static int[][] b;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
m = scan.nextInt();
q = scan.nextInt();
a = new int[n + 5][m + 5];
b = new int[n + 5][m + 5];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j] = scan.nextInt();
insert(i,j,i,j,a[i][j]);
}
}
while (q-- > 0) {
int x1= scan.nextInt();
int y1= scan.nextInt();
int x2= scan.nextInt();
int y2= scan.nextInt();
int c= scan.nextInt();
insert(x1,y1,x2,y2,c);
}
for (int i = 1; i <=n ; i++) {
for (int j = 1; j <= m; j++) {
b[i][j]=b[i-1][j]+b[i][j-1]-b[i-1][j-1]+b[i][j];
System.out.print(b[i][j]+" ");
}
System.out.write('\n');
}
}
static void insert(int x1, int y1,int x2,int y2,int c) {
b[x1][y1] += c;
b[x1][y2+1] -= c;
b[x2+1][y1] -= c;
b[x2+1][y2+1] += c;
}
}