zoukankan      html  css  js  c++  java
  • Hdu1166单点更新线段树

    入门线段树,单点更新。写了几遍,都是学着notonlysuccess写的。

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <climits>
    #include <string>
    #include <iostream>
    #include <map>
    #include <cstdlib>
    #include <list>
    #include <set>
    #include <queue>
    #include <stack>
    
    using namespace std;
    #define lson l,mid,rt<<1
    #define rson mid+1,r,rt<<1|1
    int sum[444444];
    void up(int rt)
    {
        sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
    }
    
    void build(int l, int r, int rt)
    {
        if (l == r){
            scanf("%d", &sum[rt]); return;
        }
        int mid = (l + r) >> 1;
        build(lson);
        build(rson);
        up(rt);
    }
    
    void update(int key, int add, int l, int r, int rt)
    {
        if (l == r){
            sum[rt] += add; return;
        }
        int mid = (l + r) >> 1;
        if (key <= mid) update(key, add, lson);
        else update(key, add, rson);
        up(rt);
    }
    
    int ask(int L, int R, int l, int r, int rt)
    {
        if (L <= l&&r <= R) return sum[rt];
        int mid = (l + r) >> 1;
        int ans = 0;
        if (L <= mid) ans += ask(L, R, lson);
        if (R>mid) ans += ask(L, R, rson);
        return ans;
    }
    char str[100];
    int main()
    {
        int Icase; int n;
        scanf("%d", &Icase);
        int tt = 0;
        while (Icase--){
            printf("Case %d:
    ", ++tt);
            scanf("%d", &n);
            build(1, n, 1);
            for (;;){
                int a; int b;
                scanf("%s", str); if (str[0] == 'E') break; scanf("%d%d", &a, &b);
                if (str[0] == 'A'){
                    update(a, b, 1, n, 1);
                }
                if (str[0] == 'S'){
                    update(a, -b, 1, n, 1);
                }
                if (str[0] == 'Q'){
                    printf("%d
    ", ask(a, b, 1, n, 1));
                }
            }
        }
        return 0;
    }
  • 相关阅读:
    Jzoj5408 Dark
    Jzoj5407 Deep
    Jzoj5407 Deep
    Jzoj5456【NOIP2017提高A组冲刺11.6】奇怪的队列
    Jzoj5456【NOIP2017提高A组冲刺11.6】奇怪的队列
    Jzoj5455【NOIP2017提高A组冲刺11.6】拆网线
    Codeforces Round #621 (Div. 1 + Div. 2)C
    Codeforces Round #621 (Div. 1 + Div. 2)B Cow and Friend
    PAT甲级——A1031 Hello World for U
    PAT甲级——A1029 Median
  • 原文地址:https://www.cnblogs.com/yigexigua/p/3928225.html
Copyright © 2011-2022 走看看