wikioi 1082 线段树练习 3

http://wikioi.com/problem/1082/

线段树,区间更新,区间求和,最好用到懒散标记。

线段树的学习,可以参考

http://www.notonlysuccess.com/index.php/segment-tree-complete/

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
# define inf -10000000
long long sum[800100],tag[800100];
void pushup(int root)//向上更新sum
{
    sum[root] = sum[2*root] + sum[2*root + 1];
}
void pushdown(int root,int num)//向下修改,更新左右孩子
{
    tag[2*root] += tag[root];
    tag[2*root + 1] += tag[root];
    sum[2*root] +=(num - num/2) * tag[root];
    sum[2*root + 1] += (num/2) * tag[root];
    tag[root] = 0;//tag  标记为0
}
void build(int l,int r,int root)
{
    tag[root] = 0;//tag  初始化
    if(l == r)
    {
        scanf("%lld",&sum[root]);
        return ;
    }
    else
    {
        int mid = (l+r)/2;
        build(l,mid,2*root);//建立左子树
        build(mid+1,r,2*root+1);//建立右子树
        pushup(root);
    }
}
void update(int L,int R,int v,int l,int r,int root)
{
    if(L <= l && R >= r)//找到区间,更新sum  并修改 懒散标记
    {
        sum[root] += (r - l + 1)*v; // 区间内每个值都增加
        tag[root] += v;
        return ;
    }
    pushdown(root,r-l+1);
    int mid = (l+r)/2;
    if(L <= mid)update(L,R,v,l,mid,2*root);
    if(R>mid)update(L,R,v,mid+1,r,2*root+1);
    pushup(root);// 向上传递sum
}
long long getsum(int L,int R,int l,int r,int root)
{
    if(L<= l && R >= r) return sum[root];//找到查询区间,返回sum 值
    pushdown(root,r-l+1);// 向下边修改边查询,查询过程中访问到的区间会用到增量
    int mid = (l + r)/2;
    long long res = 0;
    if(L <= mid) res += getsum(L,R,l,mid,2*root);
    if(R>mid) res += getsum(L,R,mid+1,r,2*root+1);
    return res;
}

int main()
{
    int n,m,a,b,c,d;
    scanf("%d",&n);
    build(1,n,1);
    scanf("%d",&m);
    while(m--)
    {
        scanf("%d%d%d",&a,&b,&c);
        if(a == 1)
        {
            scanf("%d",&d);
            update(b,c,d,1,n,1);
        }
        else
        {
            printf("%lld\n",getsum(b,c,1,n,1));
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值