对 从a[x1][y1]到a[x2][y2]区间的数都+c 即以下:
s[x1][y1]+=c;
s[x2+1][y1]-=c;
s[x1][y2+1]-=c
s[x2+1][y2+1]+=c;
然后在对s差分数组求二维的前缀和s[x][y]+=s[x-1][y]+s[x][y-1]-s[x-1][y-1]
最后答案就是s[i][j]+a[i][j];
package _acwing算法基础;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class _798差分矩阵
{
private static int N=1010;
private static int[][] a=new int[N][N];
private static int[][] b=new int[N][N];
public static void main(String[] args) throws IOException
{
Scanner scan=new Scanner(System.in);
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out));
int n=scan.nextInt();
int m=scan.nextInt();
int q=scan.nextInt();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
a[i][j]=scan.nextInt();
// for(int i=1;i<=n;i++)
// for(int j=1;j<=m;j++)
// 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];
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
out.write(b[i][j]+a[i][j]+" ");
//System.out.print(b[i][j]+" ");
}
out.write("\n");
//System.out.println();
}
out.flush();
scan.close();
}
private static 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;
}
}