poj3468A Simple Problem with Integers区间和线段树

本文介绍了一种使用线段树实现区间更新和查询的方法,包括构建、更新和查询操作的具体实现。通过预处理和递归操作,可以高效地解决区间修改及求和等问题。

同上。。。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <string>
#include <iostream>
#include <map>
#include <cstdlib>
#include <list>
#include <set>
#include <queue>
#include <stack>
#include<math.h>
using namespace std;
typedef long long LL;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
LL sum[444444];
LL color[444444];
void up(LL rt)
{
    sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}

void down(LL rt, LL len)
{
    if (color[rt]){
        color[rt << 1] += color[rt];
        color[rt << 1 | 1] += color[rt];
        LL mid = len >> 1;
        sum[rt << 1] += color[rt] * (len - mid);
        sum[rt << 1 | 1] += color[rt] * mid;
        color[rt] = 0;
    }
}
void build(LL l, LL r, LL rt)
{
    color[rt] = 0;
    if (l == r){
        scanf("%I64d", &sum[rt]); return;
    }
    LL mid = (l + r) >> 1;
    build(lson);
    build(rson);
    up(rt);
}
void update(LL L, LL R, LL ad, LL l, LL r, LL rt)
{
    if (L <= l&&r <= R){
        sum[rt] += ad*(r - l + 1); color[rt] += ad; return;
    }
    down(rt, r - l + 1);
    LL mid = (l + r) >> 1;
    if (L <= mid) update(L, R, ad, lson);
    if (R>mid) update(L, R, ad, rson);
    up(rt);

}

LL ask(LL L, LL R, LL l, LL r, LL rt)
{
    if (L <= l&&r <= R) return sum[rt];
    LL mid = (l + r) >> 1;
    LL ans = 0;
    down(rt, r - l + 1);
    if (L <= mid) ans += ask(L, R, lson);
    if (R>mid) ans += ask(L, R, rson);
    return ans;
}
int main()
{
    LL n, m; LL a, b, c;
    char str[100];
    while (~scanf("%I64d%I64d", &n, &m)){
        build(1, n, 1);
        for (LL i = 0; i<m; i++){
            scanf("%s", str);
            scanf("%I64d%I64d", &a, &b);
            if (str[0] == 'C'){
                scanf("%I64d", &c);
                update(a, b, c, 1, n, 1);
            }
            else{
                printf("%I64d\n", ask(a, b, 1, n, 1));
            }
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/yigexigua/p/3928265.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值