AcWing 242. A simple integer problems (Fenwick tree + differential)

Topic links: Click here
Here Insert Picture Description
Here Insert Picture Description
to Fenwick tree initialize a one-dimensional differential arrays, each time interval changes "impact" in l l generated at, in r + 1 r+1 Chu eliminate, the value is seeking an inquiry to check the score group prefix and.

Skillfully "section add" The practice + "single point of inquiry" to Fenwick tree good "single point of increase" + "range query" for processing.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long ll;
const int N = 100010;

int n, m;
int a[N];
ll tr[N];

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

void add(int x, int c)
{
    for(int i = x; i <= n; i += lowbit(i))  tr[i] += c;
}

ll sum(int x)
{
    ll res = 0;
    for(int i = x; i; i -= lowbit(i))   res += tr[i];
    return res;
}

int main()
{
    scanf("%d%d", &n, &m);
    
    for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    
    for(int i = 1; i <= n; ++i) add(i, a[i] - a[i - 1]);
    
    while(m--)
    {
        char op[2];
        scanf("%s", op);
        
        if(op[0] == 'Q')
        {
            int x;
            scanf("%d", &x);
            printf("%lld\n", sum(x));
        }
        else
        {
            int l, r, d;
            scanf("%d%d%d", &l, &r, &d);
            add(l, d);
            add(r + 1, -d);
        }
    }
    
    return 0;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105170244