A simple integer Question 2

The meaning of problems: Given a number of columns of length N A, and M instructions, each instruction may be either of the following:

   1, "C lrd", represents the A [l], A [l + 1], ..., A [r] are plus d.

   2, "Q lr", represents the number of l ~ r and the column number of interrogation.

   For each inquiry, output a integer answer.

Ideas: interval operation carried out by Fenwick tree. With an array b [i] representative of when the operation is [l, r] d operation while the b [r + 1] -d, b [l] + d. Such request prefix and suffix unchanged. Fenwick tree maintenance prefix b, corresponding to only the b [l, r] has changed,

Then use the tree-like array maintenance i * b [i] prefix. Therefore for the interval [l, r] is equal to (sum [r] + (r + 1) * ask (b, r) -ask (c, r)) - (sum [l-1] + (l-1 +1) * ask (b, l-1) -ask (c, l-1)). See how to maintain the code.

#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<cstdio>
#include<cmath>
#define ll long long
#define lowbit(x) x&(-x)
using namespace std;
const int N=2e5+10;
ll a[N],c[2][N],n,m,sum[N];
ll ask(int t,ll x)
{
    ll ans=0;
    for(;x;x-=lowbit(x))
        ans+=c[t][x];
    return ans;
}
void add(int t,ll x,ll y)
{
    for(;x<=n;x+=lowbit(x))
        c[t][x]+=y;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
        sum[i]=sum[i-1]+a[i];
    }
    while(m--)
    {
        ll l,r;
        ll t;
        ll ans;
        char s[2];
        scanf("%s",s);
        if(s[0]=='Q')
        {
            scanf("%lld%lld",&l,&r);
            ans=sum[r]+(r+1)*ask(0,r)-ask(1,r);
            ans-=sum[l-1]+l*ask(0,l-1)-ask(1,l-1);
            printf("%lld\n",ans);
        }
        else
        {
            scanf("%lld%lld%lld",&l,&r,&t);
            add(0,l,t);
            add(0,r+1,-t);
            add(1,l,l*t);
            add(1,r+1,-(r+1)*t);
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/2462478392Lee/p/11348175.html