zoukankan      html  css  js  c++  java
  • 【线段树】HDU 1166 敌兵布阵

    这道题目是线段树里面最基础的单点更新问题。
    设计的知识点包括线段树的单点更新和区间查询。
    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166
    G++代码:

    #include <cstdio>
    #include <string>
    using namespace std;
    
    #define lson l, m, rt << 1
    #define rson m+1, r, rt << 1 | 1
    
    const int maxn = 50050;
    int sum[maxn<<2];
    
    void pushUp(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 m = (l + r) >> 1;
        build(lson);
        build(rson);
        pushUp(rt);
    }
    void update(int p, int add, int l, int r, int rt) {
        if (l == r) {
            sum[rt] += add;
            return;
        }
        int m = (l + r) >> 1;
        if (p <= m) update(p, add, lson);
        else update(p, add, rson);
        pushUp(rt);
    }
    int query(int L, int R, int l, int r, int rt) {
        if (L <= l && r <= R) {
            return sum[rt];
        }
        int m = (l + r) >> 1;
        int res = 0;
        if (L <= m) res += query(L, R, lson);
        if (R >= m+1) res +=  query(L, R, rson);
        return res;
    }
    
    int T, n, cas = 1, a, b;
    char s[11];
    
    int main() {
        scanf("%d", &T);
        while (T --) {
            printf("Case %d:
    ", cas ++);
            scanf("%d", &n);
            build(1, n, 1);
            while (scanf("%s", s)) {
                if (s[0] == 'Q') {  // Query
                    scanf("%d%d", &a, &b);
                    printf("%d
    ", query(a, b, 1, n, 1));
                } else if (s[0] == 'A') {   // Add
                    scanf("%d%d", &a, &b);
                    update(a, b, 1, n, 1);
                } else if (s[0] == 'S') {   // Sub
                    scanf("%d%d", &a, &b);
                    update(a, -b, 1, n, 1);
                } else if (s[0] == 'E') {   // End
                    break;
                }
            }
        }
        return 0;
    }
    
    
  • 相关阅读:
    利用pip批量升级packages
    基于cx_freeze编译PyQt4程序(numpy & scipy)
    利用Python读取Matlab的Mat文件内容
    在PyQt4中使用matplotlib
    个人Python常用Package及其安装
    python变量不能以数字打头
    Python Django开始
    Django 1.9 支持中文(转)
    Ubuntu1604中mysql的登录问题
    h3c防火墙的设置过程
  • 原文地址:https://www.cnblogs.com/zifeiy/p/10667062.html
Copyright © 2011-2022 走看看