求前缀和运算时经常有确定数组后,频繁对数组元素进行更改,如果采用暴力解法往往会有超时问题,故时常采用差分数组求法。
基本思想为:
1.构建差分数组brr
2.对差分数组进行增删操作
3.利用规律求前缀和(此时差分数组常作为矩阵的元素作为替换)
一维替换代码如下:
//差分数组进行改变
public static void insert(int l,int r,int c){
//改变差分数组,便于前缀和求解
brr[l] += c;
brr[r + 1] -= c;
}
二维替换代码如下:
//改变差分数组
public static void insert(int x1,int y1,int x2,int y2,int c){
brr[x1][y1] += c;
brr[x2 + 1][y2 + 1] += c;
brr[x1][y2 + 1] -= c;
brr[x2 + 1][y1] -= c;
}
题目链接: 活动 - AcWing
题解:
import java.util.Scanner;
public class ChaFen {
//创建存储数组和差分数组
static int [] arr;
static int [] brr;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
arr = new int[n + 1];
brr = new int[n + 1];
//输入数据
for(int i = 0; i < n; i++){
arr[i] = scanner.nextInt();
}
//改变差分数组
for(int i = 0; i < n; i++){
insert(i,i,arr[i]);
}
while(m-- > 0){
//输入改变的区间和改变的数
int l = scanner.nextInt(),r = scanner.nextInt(),c = scanner.nextInt();
insert(l - 1,r - 1,c);
}
//求出前缀和
for(int i = 1; i < n; i++){
brr[i] += brr[i - 1];
}
//输出
for(int i = 0; i < n; i++){
System.out.print(brr[i] + " ");
}
}
//差分数组进行改变
public static void insert(int l,int r,int c){
//改变差分数组,便于前缀和求解
brr[l] += c;
brr[r + 1] -= c;
}
}
题目链接: 活动 - AcWing
题解如下:
import java.util.Scanner;
public class ChaFenJuZhen {
static int [][] arr;
static int [][] brr;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(),m = scanner.nextInt(),q = scanner.nextInt();
arr = new int[n + 2][m + 2];
//创建差分数组
brr = new int[n + 2][m + 2];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
//输入数组
arr[i][j] = scanner.nextInt();
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
insert(i,j,i,j,arr[i][j]);
}
}
//进行元素改变
while (q-- > 0){
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
int c = scanner.nextInt();
insert(x1,y1,x2,y2,c);
}
//计算前缀和
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
brr[i][j] += brr[i - 1][j] + brr[i][j - 1] - brr[i - 1][j - 1];
}
}
//输出前缀和
for (int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
System.out.print(brr[i][j] + " ");
}
System.out.println();
}
}
//改变差分数组
public static void insert(int x1,int y1,int x2,int y2,int c){
brr[x1][y1] += c;
brr[x2 + 1][y2 + 1] += c;
brr[x1][y2 + 1] -= c;
brr[x2 + 1][y1] -= c;
}
}