• hdu 1166 线段树


    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    #include<cmath>
    
    using namespace std;
    const int maxn=1000007;
    #define lson rt<<1
    #define rson rt<<1|1
    int a[maxn];
    
    struct da
    {
        int l, r;
        int s;
    } tree[maxn<<2];
    
    void build(int l, int r, int rt)
    {
        tree[rt].l = l;
        tree[rt].r = r;
    
        if(l == r)
        {
            tree[rt].s = a[l];
            return ;
        }
        int mid = (l+r)/2;
        build(l, mid, lson);
        build(mid+1, r, rson);
        tree[rt].s = tree[lson].s + tree[rson].s;
    }
    
    void update(int pos, int val, int rt)
    {
        tree[rt].s+=val;
        if(tree[rt].l==tree[rt].r)
            return ;
        int mid=(tree[rt].l+tree[rt].r)/2;
        if(pos<=mid) update(pos, val, lson);
        else update(pos, val, rson);
    }
    
    int query(int l, int r, int rt)
    {
        if(tree[rt].l==l&&tree[rt].r==r)
            return tree[rt].s;
        int mid=(tree[rt].l+tree[rt].r)/2;
        if(r<=mid)
            query(l, r, lson);
        else if(l>mid)
            query(l, r, rson);
        else
        {
            int lsum, rsum;
            lsum=query(l, mid, lson);
            rsum=query(mid+1, r, rson);
            return lsum+rsum;
        }
    }
    int main()
    {
        int T, n, cas=1;
        char op[20];
        scanf("%d", &T);
    
        while(T--)
        {
            scanf("%d", &n);
            for(int i=1; i<=n; i++)
                scanf("%d", &a[i]);
    
            build(1, n, 1);
    
            int a, b;
    
            printf("Case %d:
    ", cas++);
    
            while(scanf("%s", op), strcmp(op, "End"))
            {
                if(op[0]=='Q')
                {
                    scanf("%d%d", &a, &b);
                    printf("%d
    ", query(a, b, 1));
                    continue;
                }
                int sign=1;
                scanf("%d%d", &a, &b);
                if(op[0]=='S')
                    sign*=-1;
    
                update(a, b*sign, 1);
            }
        }
        return 0;
    }
  • 相关阅读:
    学习进度条05
    构建之法阅读笔记03
    子数组和最大值算法
    学习进度条04
    学习进度条03
    定制小学四则运算
    单元测试示例
    构建之法阅读笔记02
    学习进度条02
    decimal扩展方法(转换为字符串,去掉末尾的0)
  • 原文地址:https://www.cnblogs.com/9968jie/p/5659635.html
Copyright © 2020-2023  润新知