zoukankan      html  css  js  c++  java
  • HDU 1166 敌兵布阵

    刚学习线段树,先写一个最裸的单点更新。

    听大大们说线段树是一种非常经典而又灵活的数据结构。一步步学起吧。

    这里先写个静态的版本。 模板是模仿某位大大的。。

    #include <cstdio>
    
    #define lson rt<<1,L,M
    #define rson rt<<1|1,M + 1,R
    
    using namespace std;
    
    const int maxn = 50001;
    int sum[maxn << 2],ql,qr,val[maxn],v,tar;
    
    inline void pushup(int rt) {  //更新当前节点
        sum[rt] = sum[rt<<1] + sum[rt<<1|1];
    }
    
    void build(int rt,int L,int R) {    //建树
        if(L == R) sum[rt] = val[L];
        else {
            int M = (L + R) >> 1;
            build(lson); build(rson);
            pushup(rt);
        }
    }
    
    void update(int rt,int L,int R) {  //更新点
        if(L == R) sum[rt] += v;
        else {
            int M = (L + R) >> 1;
            if(tar <= M) update(lson);
            if(tar > M) update(rson);
            pushup(rt);
        }
    }
    
    int query(int rt,int L,int R) {  //处理查询
        if(ql <= L && qr >= R) return sum[rt];
        int M = (L + R) >> 1,ans = 0;
        if(ql <= M) ans += query(lson);
        if(qr > M) ans += query(rson);
        return ans;
    }
    
    int main() {
        int c,N;
        char cmd[10];
        scanf("%d",&c);
        for(int k = 1;k <= c;k++) {
            printf("Case %d:
    ",k);
            scanf("%d",&N);
            for(int i = 1;i <= N;i++) scanf("%d",val + i);
            build(1,1,N);
            while(scanf("%s",cmd),cmd[0] != 'E') {
                if(cmd[0] == 'Q') {
                    scanf("%d%d",&ql,&qr);
                    printf("%d
    ",query(1,1,N));
                } else {
                    scanf("%d%d",&tar,&v);
                    if(cmd[0] == 'S') v = -v;
                    update(1,1,N);
                }
            }
        }
        return 0;
    }
  • 相关阅读:
    Topics
    telnetlib-telnet客户端操作
    logging-日志信息管理
    B.2 工具spy++
    B.1 XPath 获取技巧
    pyinstaller-将Python程序打包成一个独立可执行软件包
    探讨HTTP中敏感数据的安全性传输方案
    shell->一个经典的shell脚本结构
    c->再次封装已有函数的快速方法
    c->推荐的更安全的代码写法
  • 原文地址:https://www.cnblogs.com/rolight/p/3468064.html
Copyright © 2011-2022 走看看