差分
来源 https://www.acwing.com/problem/content/799/
题目
输入一个长度为 n的整数序列。 接下来输入 m个操作,每个操作包含三个整数 l,r,c,表示将序列中 [l,r] 之间的每个数加 c。
请你输出进行完所有操作后的序列。输入格式
第一行包含两个整数 n和 m。 第二行包含 n个整数,表示整数序列。 接下来 m行,每行包含三个整数 l,r,c,表示一个操作。
输出格式
共一行,包含 n个整数,表示最终序列。
数据范围
1≤n,m≤100000,
1≤l≤r≤n,
−1000≤c≤1000,
−1000≤整数序列中元素的值≤1000输入样例:
6 3
1 2 2 1 2 1
1 3 1
3 5 1
1 6 1输出样例:
3 4 5 3 4 2
解答
构造差分数组来模拟计算过程,而不是直接在原数组上计算
package acwing;
import java.util.Scanner;
public class Acwing797 {
public static void test(int[] b, int i, int j, int c) {
b[i] += c;
if (j + 1 < b.length) {
b[j + 1] -= c;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] f = new int[n];
int[] b = new int[n];
int i = 0;
while (n > 0) {
f[i] = sc.nextInt();
n--;
test(b, i, i, f[i]);
i++;
}
while (m > 0) {
int l = sc.nextInt();
int r = sc.nextInt();
int c = sc.nextInt();
test(b, l - 1, r - 1, c);
m--;
}
sc.close();
for (int j = 0; j < b.length; j++) {
if (j == 0) {
f[j] = b[j];
} else {
f[j] = f[j - 1] + b[j];
}
System.out.print(f[j] + " ");
}
}
}