一个简单的整数问题

题目链接:https://www.acwing.com/problem/content/248/

思路:新建一个数组b,起初全为0,对于每条“ C   l   r   d”,则可以b[l]+=d,b[r+1]-=d;

          这样b数组的前缀和就是对应a数组所增加的值,只要用树状数组维护数组b即可

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#include<queue>
using namespace std;
int a[200005],b[200005];
int n;
void add(int x,int y)
{
    for(;x<=n;x+=x&-x)
        b[x]+=y;
    return;
}
int ask(int x)
{
    int ans=0;
    for(;x;x-=x&-x)
        ans+=b[x];
    return ans;
}
int main()
{
    int m;
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    while(m--)
    {
        char c;
        getchar();
        scanf("%c",&c);
        if(c=='Q')
        {
            int w;
            scanf("%d",&w);
            printf("%d\n",ask(w)+a[w]);
        }
        else
        {
            int l,r,w;
            scanf("%d %d %d",&l,&r,&w);
            add(l,w);
            add(r+1,-w);
        }
    }
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/zcb123456789/p/11370509.html