輸入一個長度為n的整數序列,
接下來輸入m個操作,每個操作包含三個整數l, r, c,表示將序列中[l, r]之間的每個數加上c,
請你輸出進行完所有操作后的序列,
輸入格式
第一行包含兩個整數n和m,
第二行包含n個整數,表示整數序列,
接下來m行,每行包含三個整數l,r,c,表示一個操作,
輸出格式
共一行,包含n個整數,表示最終序列,
資料范圍
1≤n,m≤1000001≤n,m≤100000,
1≤l≤r≤n1≤l≤r≤n,
?1000≤c≤1000?1000≤c≤1000,
?1000≤整數序列中元素的值≤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
思路:給定原陣列a[1],a[2],...a[n],構造差分陣列b[N],使得a[i] = b[1] + b[2]+ ...b[i],一般假定初始全為0,用insert(i, i, a[i])即可構造出b[N]
核心操作:將a[L~R]全部加上C,等價于:b[L] += C, b[R + 1] -= C
代碼:
import java.util.Scanner; public class Main { static final int max=100005; static int a[]=new int[max]; static int b[]=new int[max]; public static void insert(int l,int r,int c){ b[l]+=c; b[r+1]-=c; } public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int m=scan.nextInt(); for(int i=1;i<=n;i++) a[i]=scan.nextInt(); for(int i=1;i<=n;i++) insert(i,i,a[i]);//差分陣列初始化 while(m-->0){//更新操作 int l=scan.nextInt(); int r=scan.nextInt(); int c=scan.nextInt(); insert(l,r,c); } for(int i=1;i<=n;i++) b[i]+=b[i-1];//差分陣列求前綴和 for(int i=1;i<=n;i++) System.out.print(b[i]+" ");//輸出更新后的陣列 } }
實體理解:
初始化:
對于陣列b[] ,當a陣列為1,2,3,4,5
b[1]+1 b[2]-1
b[2]+2 b[3]-2
b[3]+3 b[4]-3
b[4]+4 b[5]-4
b[5]+5 b[6]-5
+操作:比如對區間[3,4]加5,b[3]+5 b[5]-5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/107640.html
標籤:其他
上一篇:kuangbin專題 專題九 連通圖 Warm up HDU - 4612
下一篇:差分模板
