线段树(小写一发)

来源:互联网 发布:在线制作手机淘宝店招 编辑:程序博客网 时间:2024/05/17 22:09

题目信息:敌兵布阵

代码:

#include<stdio.h>#include<string.h>const int maxn =50000;int sum[maxn<<2];//void pushup(int rt)//{//    sum[rt]=sum[rt<<1]+sum[(rt<<1)+1];////}//void pushup(int ret)//{//    sum[ret]=sum[ret<<1]+sum[ret<<1+1];//}//void build(int l,int r,int ret)//{//    if(l==r)//    {//        scanf("%d",sum[ret]);//        return ;//    }//    int m=(l+r)/2;//    build(l,m,ret<<1);//    build(m+1,r,ret<<1+1);//    sum[ret]=sum[ret<<1]+sum[ret<<1+1];//}void build(int l,int r,int ret){    if(l==r)    {        scanf("%d",&sum[ret]);        return ;    }    int m=(l+r)>>1;    build(l,m,ret<<1);    build(m+1,r,(ret<<1)+1);//    pushup(ret);    sum[ret]=sum[ret<<1]+sum[(ret<<1)+1];}void update(int w,int e,int l,int r,int ret){    if(l==r)    {        sum[ret]+=e;        return ;    }    int m=(l+r)>>1;    if(w<=m)        update(w,e,l,m,ret<<1);    else        update(w,e,m+1,r,(ret<<1)+1);//    pushup(ret);    sum[ret]=sum[ret<<1]+sum[(ret<<1)+1];}int query(int  w,int e,int l,int r,int ret){    if(l>=w&&r<=e)    {        return sum[ret];    }    int m=(l+r)>>1;    int ret1=0;    if(w<=m)ret1+=query( w, e, l, m,ret<<1);    if(e>m)    {        ret1+=query(w,e,m+1,r,(ret<<1)+1);    }    return ret1;}int main(){    int n;    scanf("%d",&n);    int cas=1;    while(n--)    {        printf("Case %d:\n",cas++);        int q;        scanf("%d",&q);        memset(sum,0,sizeof(sum));        build(1,q,1);        while(1)        {            char q2[10];            scanf("%s",q2);            if(q2[0]=='E')                break;//                return 0;            int w,e;            scanf("%d%d",&w,&e);            if(q2[0]=='Q')            {                printf("%d\n",query(w,e,1,q,1));            }            if(q2[0]=='A')            {                update(w,e,1,q,1);            }            if(q2[0]=='S')            {                update(w,-e,1,q,1);            }        }    }    return 0;}

0 0
原创粉丝点击