Luo Gu P3374 [template] Fenwick tree 1 (plus single point, and range)

Topic Link

https://www.luogu.org/problemnew/show/P3374

Fenwick tree

Fenwick tree is the most basic requirements and range.

maintain:

  • Space complexity: O (n)
  • Time complexity (and intervals, a single point of modification):

    Modify: O (logn)

    Query: O (logn)

With c [i] represents the (i-lowbit [i] + 1, i) and range.

Query, and the idea to use the prefix, (i, j) = c [j] -c [i-1].

advantage

The code is simple

Shortcoming

Difficult to understand

Code (resolved)

. 1 #include <the iostream>
 2 #include <cstdio>
 . 3  the using  namespace STD;
 . 4  const  int MAXN = 500 005 ;
 . 5  int n-, m;
 . 6  int C [MAXN];
 . 7  int lowbit ( int X) { // find the corresponding number a first binary 1 from the rear forward. 
. 8      return X & (- X); // example:. 6 (110) -> lowbit (. 6) = 2; 12 is (1100 is) -> lowbit (12 is) =. 4 
. 9  }
 10  void Update ( int X, int V) { // initialize and update 
11      for( Int I = X; I <= n-; + = lowbit I (I)) { // their hands Videos click 
12 is          C [I] = + V;
 13 is      }
 14  }
 15  int Query ( int X) {     // Query: and updating like, such reciprocal 
16      int RES = 0 ;
 . 17      for ( int I = X; I> 0 ; lowbit = I- (I)) = RES + C [I];
 18 is      return RES;
 . 19  }
 20 is  int main ()
 21 is  {
 22 is      CIN >> >> n- m;
 23 is      for (int i=1;i<=n;i++){
24         int v;
25         scanf("%d",&v);
26         update(i,v);
27     }
28     for(int i=1;i<=m;i++){
29         int k,x,y;
30         scanf("%d%d%d",&k,&x,&y);
31         if(k==1) update(x,y);
32         if(k==2) cout<<query(y)-query(x-1)<<endl;
33     }
34     return 0;
35 }

 

Guess you like

Origin www.cnblogs.com/yinyuqin/p/10961243.html