HDU_1166 地兵布阵

 
 
//这题也可以用树状数组来写
//这可以说是一道线段树的模板题,挺经典的啊!
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int sum;
struct node
{
    int right;
    int left;
    int value;
};
node tree[50005*4];

void Build_tree(int l,int r,int i)
{
    tree[i].left=l;
    tree[i].right=r;
    if(l==r)
    {
        scanf("%d",&tree[i].value);
        return ;
    }
    Build_tree(l,(l+r)/2,2*i);
    Build_tree((l+r)/2+1,r,2*i+1);
    tree[i].value=tree[2*i].value+tree[2*i+1].value;
}

void update(int pos,int num,int st)
{
    int mid;
    tree[st].value=tree[st].value+num;
    if(pos==tree[st].left&&pos==tree[st].right)
        return ;
    mid=(tree[st].left+tree[st].right)/2;
    if(pos<=mid)
        update(pos,num,st*2);
    else
        update(pos,num,st*2+1);
}

void Query(int i,int x,int y)
{
    int mid;
    if(x<=tree[i].left&&y>=tree[i].right)
    {
        sum=sum+tree[i].value;
        return ;
    }
    else
    {
        mid=(tree[i].left+tree[i].right)/2;
        if(x>mid)
            Query(2*i+1,x,y);
        else if(y<=mid)
            Query(2*i,x,y);
        else
        {
            Query(2*i,x,mid);
            Query(2*i+1,mid+1,y);
        }
    }
}
int main()
{
    int T,n,i,j=1,k,x,y;
    char str[20];
    scanf("%d",&T);
    while(T--)
    {
        memset(tree,0,sizeof(tree));
        printf("Case %d:\n",j++);
        scanf("%d",&n);
        Build_tree(1,n,1);
        while(cin>>str)
        {
            if(str[0]=='E')
                break;
            cin>>x>>y;
            if(str[0]=='A')
                update(x,y,1);
            else if(str[0]=='S')
                update(x,-y,1);
            else
            {
                sum=0;
                Query(1,x,y);
                printf("%d\n",sum);
            }
        }
    }
    return 0;
}

你可能感兴趣的:(tree,HDU,datebase,segment)