import java.io.BufferedInputStream; import java.util.Scanner; public class Main{ final static int maxn = 500100; static long[] tre = new long[maxn+5]; static long[] a = new long[maxn+5]; static int n,m; static void update(int x,long add) { while(x<=n) { tre[x]+=add; x+=x&(-x); } //Add add to all the jurisdictional ranges } static long sum(int x) { long s = a[x]; while(x>0) { s+=tre[x]; x-=x&(-x); }//Count all the summation information of all the intervals up to the x subscript return s; //The modified strategy is that when +add is used, it means x~maxn + add } public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); n = sc.nextInt(); m = sc.nextInt(); for(int i=1;i<=n;i++){ a[i] = sc.nextLong(); } while(m--!=0) { int f; f = sc.nextInt(); if(f==1) { int s,e; long add; s = sc.nextInt(); e = sc.nextInt(); add = sc.nextLong(); update(s,add); update(e+1,-add); //Here means s ~ e + add first } else { int x; x = sc.nextInt(); System.out.println(sum(x)); } } } }
#include<cstdio> #include<iostream> using namespace std; const int maxn = 500010; int n,m,a[maxn],c[maxn]; void update(int x,int add){ while(x<=n){ c[x]+=add; x+=x&(-x); } } int sum(int x){ int s = a[x]; while(x>0){ s+=c[x]; x-=x&(-x); } return s; } intmain() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); while(m--){ int f; scanf("%d",&f); if(f==1){ int s,e,add; scanf("%d%d%d",&s,&e,&add); update(s,add); update(e+1,-add); } else{ int x; scanf("%d",&x); printf("%d\n",sum(x)); } } return 0; }
The meaning of the question is to modify a single-point query for a data interval on an interval
Almost the same code c++ AC java three REs are too strange
No possibility to find RE at all
impossible to divide by zero
It is impossible to cross the boundary, and the range has been opened a lot, and it will not be less than zero
This problem does not need to use differential arrays at all
Just use a primitive array and modify the array
Where update(x, add) means adding add to the x~n interval
The interval modification is to add an update(e,-add)
In this way, the statistical information in the tree array is changed from the basic current number of lowbit information to the current common modification information of the x~n interval.
Then when sum(x) is used to obtain the correct sum for a single point
We need to count the modification information of all points less than x because the modification information of each point less than x is the modification of x~n
For example, for query 5, we need to obtain the information of 4 through -lowbit, and the information of 4 is the statistics of the information of (1, 2, 3, 4)