差分题目
差分:相当于反前缀和,
对于一个数组每次对于[l,r]这个区间加上s相当于对a[l]+=s,a[r+1]-s这个操作的前缀和
AC代码:
package 练习;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
static Scanner scanner=new Scanner(System.in);
static int a[],b[];
static int n,m;
public static void main(String[] args) {
n=scanner.nextInt();
m=scanner.nextInt();
a=new int [n+1];
b=new int [n+2];
for(int i=1;i<=n;i++)a[i]=scanner.nextInt();
for(int i=1;i<=n;i++)s(i, i, a[i]);
while(m-->0) {
int l=scanner.nextInt();
int r=scanner.nextInt();
int s=scanner.nextInt();
s(l, r, s);
}
for(int i=1;i<=n;i++)b[i]+=b[i-1];
for(int i=1;i<=n;i++) {
System.out.print(b[i]+" ");
}
System.out.println();
}
public static void s(int l,int r,int s) {
b[l]+=s;
b[r+1]-=s;
}
}
换快读AC代码:
import java.util.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
static Scanner scanner=new Scanner(System.in);
static int a[][],b[][];
static int n,m,q;
public static void main(String[] args) {
n=scanner.nextInt();
m=scanner.nextInt();
q=scanner.nextInt();
a=new int [n+1][m+1];
b=new int [n+2][m+2];
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
a[i][j]=scanner.nextInt();
}
}
// for(int i=1;i<=n;i++) {
// for(int j=1;j<=n;j++) {
// s(i, j, i, j, a[i][j]);
// }
// }
while(q-->0) {
int x=scanner.nextInt();
int y=scanner.nextInt();
int xx=scanner.nextInt();
int yy=scanner.nextInt();
int s=scanner.nextInt();
s(x, y, xx, yy, s);
}
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
b[i][j]=b[i][j]+b[i-1][j]+b[i][j-1]-b[i-1][j-1];
System.out.print(b[i][j]+a[i][j]+" ");
}
System.out.println();
}
}
public static void s(int x,int y, int xx,int yy,int s) {
b[x][y]+=s;
b[xx+1][y]-=s;
b[x][yy+1]-=s;
b[xx+1][yy+1]+=s;
}
}