poj 3468 A Simple Problem with Integers 线段树

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

struct node
{
    int l,r;
    long long sum,c;
}t[400000+5];

void build(int root,int l,int r)
{
    t[root].l=l;
    t[root].r=r;
    t[root].sum=0;
    t[root].c=0;
    if(l==r) return ;
    build(2*root+1,l,(l+r)/2);
    build(2*root+2,(l+r)/2+1,r);

}

void update(int root,int i,int v)
{
    if(t[root].l==i&&t[root].r==i)
    {
        t[root].sum=v;
        return ;
    }
    t[root].sum+=v;
    int mid=(t[root].l+t[root].r)/2;
    if(i<=mid)
        update(2*root+1,i,v);
    else
        update(2*root+2,i,v);
}

void add(int root,int l,int r,long long c)
{
    if(t[root].l==l&&t[root].r==r)
    {
        t[root].c+=c;
        return ;
    }
    t[root].sum+=c*(r-l+1);

    int mid=(t[root].l+t[root].r)/2;
    if(r<=mid)
        add(2*root+1,l,r,c);
    else if(l>mid)
        add(2*root+2,l,r,c);
    else
    {
        add(2*root+1,l,mid,c);
        add(2*root+2,mid+1,r,c);
    }
}

long long query(int root,int l,int r)
{
    if(t[root].l==l&&t[root].r==r)
    {
        return t[root].sum+(r-l+1)*t[root].c;
    }

    t[root].sum+=(t[root].r-t[root].l+1)*t[root].c;

    int mid=(t[root].r+t[root].l)/2;
    add(2*root+1,t[root].l,mid,t[root].c);
    add(2*root+2,mid+1,t[root].r,t[root].c);
    t[root].c=0;

    if(r<=mid)
        return query(2*root+1,l,r);
    else if(l>=mid+1)
        return query(2*root+2,l,r);
    else
    {
        return (query(2*root+1,l,mid)+query(2*root+2,mid+1,r));
    }
}

int main()
{
    int i,n,q,v,a,b;
    long long c;
    char s[10];
    while(~scanf("%d%d",&n,&q))
    {
        build(0,1,n);
        for(i=1;i<=n;i++)
        {
            scanf("%d",&v);
            update(0,i,v);
        }

        for(i=0;i<q;i++)
        {
            scanf("%s",s);
            if(s[0]=='C')
            {
                scanf("%d %d %lld",&a,&b,&c);
                add(0,a,b,c);
            }
            else if(s[0]=='Q')
            {
                scanf("%d%d",&a,&b);
                long long ans=query(0,a,b);
                printf("%lld
",ans);
            }
        }
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

原文地址:https://www.cnblogs.com/xryz/p/4847884.html