淘寶做短視頻網(wǎng)站百度第三季度財報2022
差分
題目描述
輸入一個長度為n的整數(shù)序列。
接下來輸入m個操作,每個操作包含三個整數(shù)l, r, c,表示將序列中[l, r]之間的每個數(shù)加上c。
請你輸出進行完所有操作后的序列。
輸入格式
第一行包含兩個整數(shù)n和m。
第二行包含n個整數(shù),表示整數(shù)序列。
接下來m行,每行包含三個整數(shù)l,r,c,表示一個操作。
輸出格式
共一行,包含n個整數(shù),表示最終序列。
數(shù)據(jù)范圍1≤n,m≤100000,
1≤l≤r≤n,
?1000≤c≤1000,
?1000≤整數(shù)序列中元素的值≤1000輸入樣例:6 3
1 2 2 1 2 1
1 3 1
3 5 1
1 6 1輸出樣例:3 4 5 3 4 2
Solution
import java.util.*;
import java.io.*;public class Main{public static void main(String[] args) throws IOException{BufferedReader in = new BufferedReader(new InputStreamReader(System.in));String[] s = in.readLine().split(" ");// 整數(shù)序列 n 個整數(shù)int n = Integer.parseInt(s[0]);// m 個插入操作// 插入操作對于數(shù)組的索引是從 1 開始的// 所以建立差分數(shù)組也是從從 1 開始,比較不容易出錯int m = Integer.parseInt(s[1]);s = in.readLine().split(" ");int[] a = new int[n + 10];for(int i = 1; i <= n; i++){int c = Integer.parseInt(s[i - 1]);// 插入 cinsert(a, i, i, c);}while(m > 0){m--;s = in.readLine().split(" ");int l = Integer.parseInt(s[0]);int r = Integer.parseInt(s[1]);int c = Integer.parseInt(s[2]);insert(a, l, r, c);}for(int i = 1; i <= n; i++){a[i] += a[i - 1];System.out.print(a[i] + " ");}}public static void insert(int[] a, int l, int r, int c){a[l] += c;a[r + 1] -= c;}}