题目 HDU 1166 敌兵布阵

线段树。加法。

代码

View Source On GitHub

#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;


int C[131072];

char cmd[32];

int getsum(int left,int right,int pos,int leftbound,int rightbound)
{
    if(left<=leftbound&&right>=rightbound)
    {
        return C[pos];
    }
    if(right<leftbound||left>rightbound)
    {
        return 0;
    }
    int a=getsum(left,right,2*pos+1,leftbound,(leftbound+rightbound)/2);
    int b=getsum(left,right,2*pos+2,(leftbound+rightbound)/2+1,rightbound);
    return a+b;
}
int main()
{
    int t;
    scanf("%d",&t);
    for(int itt=1;itt<=t;itt++)
    {
        printf("Case %d:\n",itt);
        int N;
        scanf("%d",&N);
        int realn=1;
        while(realn<N)
        {
            realn*=2;
        }
        memset(C,0,sizeof(int)*realn);
        for(int i=0;i<N;i++)
        {
            scanf("%d",&C[realn-1+i]);
        }
        int start=(realn-1)/2;
        while(start>0)
        {
            int L=start+1;
            for(int i=0;i<L;i++)
            {
                C[start+i]=C[2*(start+i)+1]+C[2*(start+i)+2];
            }
            start=(start-1)/2;
        }
        C[0]=C[1]+C[2];
        while(scanf("%s",cmd)==1)
        {
            if(strcmp(cmd,"End")==0)
            {
                break;
            }
            int a,b;
            scanf("%d %d",&a,&b);
            if(strcmp(cmd,"Query")==0)
            {
                int ans=getsum(a-1,b-1,0,0,realn-1);
                printf("%d\n",ans);
            }
            else if(strcmp(cmd,"Add")==0)
            {
                int pos=realn-1+a-1;
                while(pos>0)
                {
                    C[pos]+=b;
                    pos=(pos-1)/2;
                }
                C[0]+=b;
            }
            else if(strcmp(cmd,"Sub")==0)
            {
                int pos=realn-1+a-1;
                while(pos>0)
                {
                    C[pos]-=b;
                    pos=(pos-1)/2;
                }
                C[0]-=b;
            }
        }
    }/// end of for(...)

    return 0;
}

我在GitHub上建立了一个仓库,用于存放已经AC的题目的源代码。如果各位有未收录的题目或者有更好的解法,欢迎fork仓库+PR~ 让我们共同创建一个AC代码集中仓库,造福ACM Beginner ~

仓库地址: OJ-Problems-Source On GitHub


Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐