AcWing 242. A simple integer problem difference + tree array

AcWing 242. A simple integer problem

Given a number sequence A of length N, then input M lines of operation instructions.

The first type of instruction is in the form of "C lrd", which means to add d to all the l~r numbers in the sequence.

The second type of instruction is in the form of "QX", which means the value of the xth number in the query sequence.

For each query, output an integer to indicate the answer.

Input format The
first line contains two integers N and M.

The second line contains N integers A[i].

The next M lines represent M instructions, and the format of each instruction is shown in the title description.

Output format
For each query, an integer is output to represent the answer.

Each answer occupies one line.

Data range
1≤N,M≤105,
|d|≤10000,
|A[i]|≤1000000000
Input example:

10 5
1 2 3 4 5 6 7 8 9 10
Q 4
Q 1
Q 2
C 1 6 3
Q 2

Sample output:

4
1
2
5

This question is a simple integer problem as mentioned in the title. Let us ask for what is a number. We use difference and tree array to solve this problem. Why use tree array, because add and query The operation is fast.

code show as below:

#include<iostream>

using namespace std;

typedef long long LL;

const int N=1e5+10;

LL trie[N],a[N];
int n,m;

int lowbit(int x)
{
    
    
    return x&(-x);
}

void add(int k,int v)
{
    
    
    for(int i=k;i<=n;i+=lowbit(i)) trie[i]+=v;
}

LL query(int k)
{
    
    
    LL res=0;
    for(int i=k;i;i-=lowbit(i))
    res+=trie[i];
    return res;
}

int main(void)
{
    
    
    cin>>n>>m;
    for(int i=1;i<=n;i++) 
    {
    
    
        cin>>a[i];
        add(i,a[i]-a[i-1]);
    }
    while(m--)
    {
    
    
        char op;
        cin>>op;
        if(op=='Q')
        {
    
    
            int t;
            cin>>t;
            cout<<query(t)<<endl;
        }
        else
        {
    
    
            int l,r,v;
            cin>>l>>r>>v;
            add(l,v);add(r+1,-v);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_52358098/article/details/114237052