Luogu P3368 [Template] Tree array 2 (tree array + difference)

Title description

For example, given a sequence, you need to perform the following two operations:

  1. Add xx x to each number in a range ;

  2. Find the value of a certain number.

Input format

The first row contains two integers NN N, MM M, which represent the number of numbers in the series and the total number of operations.

The second line contains NN N integers separated by spaces, where the ii i number represents the initial value of the ii i item of the sequence .

Next, the MM M lines each comprising 22 is 2 or 44 is four integer representing an operation, as follows:

Operation 11 1: Format: 1 x y kMeaning: Add kk k to each number in the interval [x, y] [x, y] [ x , y ] ;

Operation 22 2: Format: 2 xMeaning: Output the xx xth value.

Output format

The output contains several lines of integers, which are the results of all operations 22 2.

Sample input and output

Enter # 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 
In fact, the tree-like array can be modified by means of difference, and because difference and prefix sum can be regarded as reciprocal operations, the value of the ask function can even be output directly in the final single-point query.
For interval modification (this question is to add / subtract a number to the interval at the same time, in fact, the function of the tree array is not as powerful as the line tree), use the tree array to maintain a difference sequence, for [l, r] add k, Just add (x, k) add (y + 1, -k).
#include <bits/stdc++.h>
using namespace std;
int n,m,a[500005]={0},b[500005];
int ask(int x)
{
    int ans=0;
    for(; x; x -= x & -x) ans += b[x];
    return ans;
}
void add(int x,int y)
{
    for(; x <= n; x += x & -x) b[x] += y;
}
int main ()
{
    cin>>n>>m;
    int i;
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        add (i, a [i] -a [i- 1 ]); // Note to initialize in this way 
    }
     for (i = 1 ; i <= m; i ++ )
    {
        int choose;
        scanf("%d",&choose);
        if(choose == 1)
        {
            int x,y,k;
            scanf("%d%d%d",&x,&y,&k);
            add(x,k),add(y+1,-k);//?
        }
        else
        {
            int x;
            scanf("%d",&x);
            cout<<ask(x)<<endl;
        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lipoicyclic/p/12693484.html