zoukankan      html  css  js  c++  java
  • BZOJ3212: Pku3468 A Simple Problem with Integers

    【传送门:BZOJ3212


    简要题意:

      给出一段序列,有两种操作:
      1.Q l r求出l到r的和

      2.C l r c将l到r的值加c


    题解:

      线段树水题

      区间修改+区间询问,加个标记处理

      注意加long long


    参考代码:

    #include<cstdio>
    #include<cstdlib>
    #include<algorithm>
    #include<cmath>
    #include<cstring>
    using namespace std;
    typedef long long LL;
    struct node
    {
        int l,r,lc,rc;
        LL c,lazy;
    }tr[210000];int trlen;
    LL a[110000];
    void bt(int l,int r)
    {
        trlen++;int now=trlen;
        tr[now].l=l;tr[now].r=r;tr[now].c=0;
        tr[now].lc=tr[now].rc=-1;tr[now].lazy=0;
        if(l==r) tr[now].c=a[l];
        else
        {
            int mid=(l+r)/2;
            tr[now].lc=trlen+1;bt(l,mid);
            tr[now].rc=trlen+1;bt(mid+1,r);
            tr[now].c=tr[tr[now].lc].c+tr[tr[now].rc].c;
        }
    }
    void update(int now)
    {
        int lc=tr[now].lc,rc=tr[now].rc;
        if(lc!=-1) tr[lc].c+=LL(tr[lc].r-tr[lc].l+1)*tr[now].lazy,tr[lc].lazy+=tr[now].lazy;
        if(rc!=-1) tr[rc].c+=LL(tr[rc].r-tr[rc].l+1)*tr[now].lazy,tr[rc].lazy+=tr[now].lazy;
        tr[now].lazy=0;
    }
    void change(int now,int l,int r,int c)
    {
        if(tr[now].l==l&&tr[now].r==r)
        {
            tr[now].c+=LL(r-l+1)*c;
            tr[now].lazy+=c;
            return ;
        }
        int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2;
        if(tr[now].lazy!=0) update(now);
        if(r<=mid) change(lc,l,r,c);
        else if(l>mid) change(rc,l,r,c);
        else change(lc,l,mid,c),change(rc,mid+1,r,c);
        tr[now].c=tr[lc].c+tr[rc].c;
    }
    LL getsum(int now,int l,int r)
    {
        if(tr[now].l==l&&tr[now].r==r) return tr[now].c;
        int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2;
        if(tr[now].lazy!=0) update(now);
        if(r<=mid) return getsum(lc,l,r);
        else if(l>mid) return getsum(rc,l,r);
        else return getsum(lc,l,mid)+getsum(rc,mid+1,r);
    }
    int main()
    {
        int n,q;
        scanf("%d%d",&n,&q);
        for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
        trlen=0;bt(1,n);
        char st[11];
        for(int i=1;i<=q;i++)
        {
            int l,r;LL c;
            scanf("%s%d%d",st+1,&l,&r);
            if(st[1]=='Q') printf("%lld
    ",getsum(1,l,r));
            else
            {
                scanf("%lld",&c);
                change(1,l,r,c);
            }
        }
        return 0;
    }

     

  • 相关阅读:
    Java实现 LeetCode 343 整数拆分(动态规划入门经典)
    Java实现 LeetCode 342 4的幂
    Java实现 LeetCode 342 4的幂
    Java实现 LeetCode 342 4的幂
    Java实现 LeetCode 341 扁平化嵌套列表迭代器
    Java实现 LeetCode 341 扁平化嵌套列表迭代器
    Java实现 LeetCode 341 扁平化嵌套列表迭代器
    Java实现 LeetCode 338 比特位计数
    H264(NAL简介与I帧判断)
    分享一段H264视频和AAC音频的RTP封包代码
  • 原文地址:https://www.cnblogs.com/Never-mind/p/8637899.html
Copyright © 2011-2022 走看看