AcWing 797. 差分
原题链接
简单
作者:
funny
,
2020-01-02 17:35:37
,
所有人可见
,
阅读 891
import java.util.*;
import java.io.*;
class Main{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
/*
1.对数组进行初始化操作: a[1] a[2] a[3] a[4] ...... a[n]
2.对数组进行差分结果是: a[1] a[2] -a[1] a[3] - a[2] a[4] - a[3] ...... a[n] - a[n - 1]
*/
String[] s2 = br.readLine().split(" ");
int[] a = new int[n + 1];
int[] b = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = Integer.parseInt(s2[i - 1]);
// insert(i, i, a[i], b); // b[i] = a[i] - a[i - 1]
b[i] = a[i] - a[i - 1] ;
}
/*
相当于后面执行 b[i] += b[i - 1] 会给 l以后的都加上c, 所以在 r 时, 要减去c
*/
while(m-- > 0) {
String[] s3 = br.readLine().split(" ");
int l = Integer.parseInt(s3[0]);
int r = Integer.parseInt(s3[1]);
int c = Integer.parseInt(s3[2]);
//差分执行insert操作,相当于前缀和执行题目要求;
insert(l, r, c, b);
}
for (int i = 1; i <= n; i++) {
b[i] += b[i - 1];
System.out.print(b[i] + " ");//通过差分构造前缀和;
}
br.close();
}
public static void insert(int l, int r, int c, int[] arr) {
arr[l] += c;
if (r < arr.length - 1) {
arr[r + 1] -= c;
}
}
}