码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构 线段树模板

时间:2018-03-29 15:59:16      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:ring   memset   hup   build   --   UI   include   def   cas   

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define CLR(a,b) memset(a,b,sizeof(a))
using namespace std;
#define maxn 50010
int Sum[maxn<<2],Add[maxn<<2];
int n,A[maxn];

void PushUp(int rt)
{
    Sum[rt] = Sum[rt<<1] + Sum[rt<<1|1];
}

void Build(int l,int r,int rt)
{
    if( r == l ){
        Sum[rt] = A[l];
        return ;
    }
    int m = (r+l)>>1;

    Build(l,m,rt<<1);
    Build(m+1,r,rt<<1|1);

    PushUp(rt);
}

void PushDown(int rt,int ln,int rn)
{
    if(Add[rt]){
        Add[rt>>1] += Add[rt];
        Add[rt>>1|1] += Add[rt];

        Sum[rt>>1] += Add[rt]*ln;
        Sum[rt>>1|1] += Add[rt]*rn;
    }
    Add[rt] = 0;
}

void Update(int L,int R,int c,int l,int r,int rt)
{
    if( l >= L && r <= R ){
        Sum[rt] += c*(r-l+1);
        Add[rt] += c;
        return ;
    }
    int m = (r+l)>>1;
    PushDown(rt,m-l+1,r-m);

    if(L<=m) Update(L,R,c,l,m,rt<<1);
    if(R>m)  Update(L,R,c,m+1,r,rt<<1|1);
    PushUp(rt);
}

int Query(int L,int R,int l,int r,int rt)
{
    if( l >= L && r <= R){
        return Sum[rt];
    }
    int m = (r+l)>>1;
    PushDown(rt,m-l+1,r-m);

    int Ans = 0;
    if(L<=m) Ans += Query(L,R,l,m,rt<<1);
    if(R> m) Ans += Query(L,R,m+1,r,rt<<1|1);
    return Ans;
}

int main()
{
    int n,m,k=0;
    cin>>n;
    while(n--){
        cout<<"Case "<<++k<<":"<<endl;
        cin>>m;
        for(int i=1;i<=m;i++)
            scanf("%d",&A[i]);
        Build(1,m,1);

        char a[10],ch;
        int b,c;

        while(scanf("%c%s",&ch,a)!=EOF){
            if(a[0] == ‘E‘)
                break;
            scanf("%d%d",&b,&c);

            if(a[0] == ‘Q‘){
                cout<<Query(b,c,1,m,1)<<endl;
            }

            if(a[0] == ‘A‘){
                Update(b,b,c,1,m,1);
            }

            if(a[0] == ‘S‘){
                Update(b,b,c*-1,1,m,1);
            }
        }


        CLR(Sum,0);
        CLR(Add,0);
    }
    return 0;
}

数据结构 线段树模板

标签:ring   memset   hup   build   --   UI   include   def   cas   

原文地址:https://www.cnblogs.com/Tokisaki-Kurumi-/p/8669915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!