HDU 1166再来一个基础线段树

来源:互联网 发布:d3.js 力学图 编辑:程序博客网 时间:2024/06/05 18:29

这个是第二个线段树的题目了,在搞懂了一个题目之后这个写起来就顺手多了,几乎完全就自己能够给A掉了,很开心啊。很经典的单点变化的线段树啊。

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define lson l, m, rt<<1#define rson m+1, r, rt<<1|1#define mid int m = (l + r)>>1const int maxn=50010;int t,n,a[maxn];char s[maxn];struct node{    int num,l,r;}tree[maxn<<2];void build(int l,int r,int rt){    tree[rt].l=l;    tree[rt].r=r;    tree[rt].num=0;    if(l==r)     {         tree[rt].num=a[l];         return ;     }    mid;    build(lson);    build(rson);    tree[rt].num=tree[rt<<1].num+tree[rt<<1|1].num;}void update_add(int l,int r,int rt,int x,int y){    if(l==r&&l==x)    {        tree[rt].num+=y;        return ;    }    mid;    if(x<=m) update_add(lson,x,y);    else        update_add(rson,x,y);    tree[rt].num=tree[rt<<1].num+tree[rt<<1|1].num;}void update_sub(int l,int r,int rt,int x,int y){    if(l==r&&l==x)    {        tree[rt].num=tree[rt].num-y;        return ;    }    mid;    if(x<=m) update_sub(lson,x,y);    else        update_sub(rson,x,y);    tree[rt].num=tree[rt<<1].num+tree[rt<<1|1].num;}int query(int l,int r,int rt,int x,int y){    if(x<=l&&y>=r)        return tree[rt].num;    mid;    int ans=0;    if(x<=m)        ans+=query(lson,x,y);    if(y>m)        ans+=query(rson,x,y);    return ans;}int main(){    int kase=1;    scanf("%d",&t);    while(t--)    {       printf("Case %d:\n",kase++);       scanf("%d",&n);       for(int i=1;i<=n;i++)        scanf("%d",&a[i]);       build(1,n,1);       while(scanf("%s",s)!=EOF)       {           if(s[0]=='E')            break;            int x,y;           scanf("%d%d",&x,&y);           if(!strcmp(s,"Add"))            update_add(1,n,1,x,y);           else if(!strcmp(s,"Sub"))            update_sub(1,n,1,x,y);           else if(!strcmp(s,"Query"))            printf("%d\n",query(1,n,1,x,y));       }    }    return 0;}


0 0
原创粉丝点击