Fenwick tree (zone changes, a single point of inquiry)

Title Description

If that is known to a number of columns, you need to perform the following two operations:

1. Each section plus a few number x

Obtaining a value of 2. The number of

Input and output formats

Input formats:

 

The first line contains two integers N, M, respectively, represents the number of the total number of columns and number of operations.

The second line contains N integers separated by spaces, wherein the number indicates the i-th column of the item i of the initial value.

Next M lines contains an integer of 2 or 4, it indicates an operation as follows:

Operation 1: Format: 1 XYK Meaning: the interval [x, y] k each number plus

Operation 2: Format: 2 x Meaning: the number of x-value output

 

Output formats:

 

Output contains an integer number of lines, that is, the operation results of all 2.

 1 #include<iostream>
 2 #include<cstdio> 
 3 using namespace std;
 4 
 5 long long n,m;
 6 long long a[500009]; 
 7 long long b[500009];
 8 long long lowbit(int x)
 9 {
10     return (x&(-x));
11 }
12 void change(int x,int k)
13 {
14     for(int i=x;i<=n;i+=lowbit(i))
15     {
16         b[i]+=k;
17     }
18 }
19 long long query(int x)
20 {
21     long long sum=0;
22     for(int i=x;i>=1;i-=lowbit(i))
23     {
24         sum+=b[i];
25     }
26     return sum;
27 }
28 int main()
29 {
30     cin>>n>>m;
31     for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
32     for(int i=1;i<=m;i++)
33     {
34         int p;
35         cin>>p;
36         if(p==1)
37         {
38             int x,y,k;
39             scanf("%d %d %d",&x,&y,&k);
40             change(x,k);
41             change(y+1,-k);
42         }
43         if(p==2)
44         {
45             int x;
46             scanf("%d",&x);
47             cout<<query(x)+a[x]<<endl;
48         }
49     }
50 }

 

Guess you like

Origin www.cnblogs.com/1129-tangqiyuan/p/11220997.html