这是第二次写这道题的题解了,上次是用树状数组写的。
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
/* 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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zhang_xueping/article/details/47679357