hdu1166(线段树模版,区间求和)

http://acm.hdu.edu.cn/showproblem.php?pid=1166

用线段树做,比树状数组费时

#include<iostream>
using namespace std;
const int N=50005;
struct 
{
    int left,right,num;
}s[4*N];
int data[N];
void build(int left,int right,int n)
{
    int mid;
    mid=(left+right)/2;
    if(left==right)
    {
        s[n].left=left;
        s[n].right=right;
        s[n].num=data[left];
    }
    else
    {
        s[n].left=left;
        s[n].right=right;
        build(left,mid,n*2);
        build(mid+1,right,n*2+1);
        s[n].num=s[n*2].num+s[n*2+1].num;
    }
}
int sum(int left,int right,int n)
{
    int mid=(s[n].left+s[n].right)/2;
    if(s[n].left==left&&s[n].right==right)
    {
        return s[n].num;
    }
    else
        if(left>mid)
            sum(left,right,n*2+1);
        else
            if(right<=mid)
                sum(left,right,n*2);
            else
                return (sum(left,mid,n*2)+sum(mid+1,right,n*2+1));
}
void add(int i,int j,int n)
{
    int mid=(s[n].left+s[n].right)/2;
    if(s[n].left==i&&s[n].right==i)
    {
        s[n].num+=j;
        int count=n/2;
        while(count>=1)
        {
            s[count].num+=j;
            count/=2;
        }
    }
    else
        if(i>mid)
            add(i,j,n*2+1);
        else
            if(i<=mid)
                add(i,j,n*2);
}
int main()
{
    int t,f=0;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&data[i]);
        build(1,n,1);
        getchar();
        printf("Case %d:\n",++f);
        char s[10];
        scanf("%s",s);
        while(1)
        {
            if(s[0]=='Q')
            {
                int x,y;
                scanf("%d%d",&x,&y);
                printf("%d\n",sum(x,y,1));
            }
            else
                if(s[0]=='A')
                {
                    int x,y;
                    scanf("%d%d",&x,&y);
                    add(x,y,1);
                }
                else
                    if(s[0]=='S')
                    {
                        int x,y;
                        scanf("%d%d",&x,&y);
                        add(x,-y,1);
                    }
                    else
                        if(s[0]=='E')
                            break;
                        getchar();
                        scanf("%s",s);
        }
    }
    return 0;
}


 

posted @ 2012-11-23 08:40  紫忆  阅读(174)  评论(0编辑  收藏  举报