P3368 [template] Fenwick tree 2 (achieve a single point of inquiry interval & modify)

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 Format

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 Format

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

Sample input and output

Input # 1
5 5
1 5 4 2 3
1 2 4 2
2 3
1 1 5 -1
1 3 5 7
2 4
Output # 1
6
10

Description / Tips

Constraints of time: 1000ms, 128M

Data Scale:

For 30% of the data: N <= 8, M <= 10

For 70% of the data: N <= 10000, M <= 10000

To 100% of the data: N <= 500000, M <= 500000

#include <the iostream>
 the using  namespace STD;
 const  int INF = 500000 ;
 int A [INF], C [INF * 2 ];
 int n-, m; 
 int lowbit ( int X) 
{ 
    return X & the -X-; // find CMP ( 2, k) k is the number 0 at the end, but also the position of the end of the seek 1 
}
 void Update ( int X, int K) 
{ 
    the while (X <= n-) 
    { 
        C [X] = C [X] + K; 
        X X + = lowbit (X); 
    } 
} 
int Quary (int x)
{
    int sum=0;
    while(x>0)
    {
        sum=sum+c[x];
        x=x-lowbit(x);
    }
    return sum;
}
int main()
{
    int op,x,k,y,now=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        update(i,a[i]-now);
        now=a[i];
    }
    while(m--)
    {
        cin>>op;
        if(op==1)
        {
            cin>>x>>y>>k;
            update(x,k);
            update(y+1,-k);
        }
        else if(op==2)
        {
            cin>>x;
            cout<<quary(x)<<endl;
        }
    }
    return 0;
}

Use the ideological differences

To introduce differential

Provided array a [] = {1,6,8,5,10}, then the difference array b [] = {1,5,2, -3,5}

That is b [i] = a [i] -a [i-1]; (a [0] = 0;), then a [i] = b [1] + .... + b [i] ; (this is a nice certificate).

If the interval [2,4] are words plus 2

becomes a array a [] = {1,8,10,7,10}, b array becomes b = {1,7,2, -3,3};

Is not found, b only the array b [2] and b [5] has changed, because the interval [2,4] plus 2 simultaneously, so that in the interval b [i] -b [i-1] is not changing.

So the interval [x, y] be modified, only the modification b [x] and b [y + 1]:

b[x]=b[x]+k;b[y+1]=b[y+1]-k;

Guess you like

Origin www.cnblogs.com/liuzhaojun/p/11274178.html