HDU 1166 敌兵布阵(线段树)

18 篇文章 0 订阅
15 篇文章 0 订阅

这是第二次写这道题的题解了,上次是用树状数组写的。

http://blog.csdn.net/zhang_xueping/article/details/47123951


虽然在去年暑假的时候曾经试过学习线段树,但是后来由于觉得麻烦所以放弃了,碰巧遇到这道题,就百度找题解,发现树状数组的代码简单多了,就认真看了几遍,大概把模板记住了,然后自己敲出来了。当时特开心,天真的以为线段树的题目都可以用树状数组做,这样就可以暂时不用钻研线段树了,看着那个模板好长就晕%>_<%……Orz……

后来发现自己的想法实在是太幼稚了,虽说树状数组的题都可以用线段树做,但并不是所有能用线段树做的题目都可以用树状数组,没办法,还是的硬着 头皮开始啃线段树,那么还是从敌兵布阵这道题开始吧 ……

线段树是一个非常高效的数据结构。 所有能用树状数组解决的问题都可以用线段树解决。 线段树是用一个数组来维护被处理数组的信息。 复杂度是log级别的。 这里对于原始数组用a表示, 维护数组用sum表示。sum数组下标从1开始。对于当前节点rt的左孩子和有孩子分别为rt<<1, rt<<1 | 1 。常见的线段树的功能是实现点修改区间查询、区间修改点查询、区间修改区间查询等等。

这道题呢,意思也很明显,就是线段树的单点更新,线段树一般变化最大的就是询问,和更新。

在这里,我还学习了大牛们得宏定义写法:

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define root 1,n,1

题目AC 代码如下:

/*
Author:ZXPxx
Memory: 2136 KB		Time: 358 MS
Language: C++		Result: Accepted
*/


#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=50000+5;

#define lson l,m,rt<<1
#define rson m+1,r,(rt<<1)+1
#define root 1,n,1

int S[maxn*4];

void push_up(int rt) {
    S[rt] = S[rt << 1] + S[(rt << 1) + 1] ;
}

void build(int l, int r, int rt) {
    if(l == r) {
        scanf("%d", &S[rt]);
        return;
    }
    int m = (l + r) >> 1;
    build(lson);
    build(rson);
    push_up(rt);
}

void update(int x, int d, int l, int r, int rt) {
    if(l == r) {
        S[rt] += d;
        return;
    }
    int m = (l + r) >> 1;
    if(x <= m) update(x, d, lson);
    else update(x, d, rson);
    push_up(rt);
}

int query(int L, int R, int l, int r, int rt) {
    if(L <= l && r <= R) {
        return S[rt];
    }
    int m = (l + r) >> 1;
    int ret=0;
    if(L<=m)
        ret += query(L,R,lson);
    if(R>m)
        ret += query(L,R,rson);
    return ret;
}

int main() {
    int n,t,x,y,cas=1;
    char str[10];
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);
        build(root);
        printf("Case %d:\n",cas++);
        while(~scanf("%s", str),str[0]!='E') {
            scanf("%d%d",&x,&y);
            if(str[0]=='Q') {
                printf("%d\n", query(x, y, root));
            } else if(str[0]=='A') {
                update(x, y, root);
            } else if(str[0]=='S') {
                update(x, -y, root);
            }
        }
    }
    return 0;
}

线段树算是比较难的算法之一了,但是适用范围很广,还是要认真学一下的。还有,线段树对递归要求有点高,递归不是很熟的同学,最好去把递归复习几遍,当然也包括鄙人自己这个患有“递归恐惧症”的啦……╮(╯▽╰)╭……



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值