hdu1166(线段树)

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 5e4+3;
struct Node//营地
{
    int beg, end, num;//区间的开始和结束位置,该区间的人数
}tree[maxn<<2]; //4倍空间
//
void build(int beg, int end, int rt)//建立线段树
{
    tree[rt].beg = beg;
    tree[rt].end = end;
    if(beg == end){//叶节点,需要输入一个数
        scanf("%d", &tree[rt].num);
        return;
    }
    int mid = (beg+end)>>1;
    build(beg, mid, rt<<1);//rt<<1:相当于rt*2
    build(mid+1, end, rt<<1|1);//相当于rt*2+1
    tree[rt].num = tree[rt<<1].num + tree[rt<<1|1].num;
}

void update(int th, int c, int rt)//点修改
{
    tree[rt].num += c;
    if(tree[rt].beg == tree[rt].end)return;

    if(tree[rt<<1].end >= th){
        update(th, c, rt<<1);
    }
    else{
        update(th, c, rt<<1|1);
    }
}

int query(int beg, int end, int rt)//区间查询
{
    if(beg <= tree[rt].beg && end >= tree[rt].end){
        return tree[rt].num;
    }
    int mid = (tree[rt].beg+tree[rt].end) >> 1;
    int ret = 0;
    if(beg <= mid) ret += query(beg, end, rt<<1);
    if(end > mid) ret += query(beg, end, rt<<1|1);
    return ret;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int t, cot = 0;
    cin >> t;
    while(t--){//t个案例
        printf("Case %d:\n",++cot);
        int n;
        char str[8];
        scanf("%d", &n);
        build(1, n, 1);

        while(scanf("%s", str) && str[0] != 'E'){
            int i, j;
            scanf("%d%d", &i, &j);
            if(str[0] == 'Q'){
                printf("%d\n", query(i, j, 1));
            }
            else if(str[0] == 'A'){
                update(i, j, 1);
            }
            else{
                update(i,-j, 1);
            }
        }
    }

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值