线段树---敌兵布阵hdoj 1166

include

include <stdio.h>

include <math.h>

using namespace std;
const int maxNode = 50005;
struct Node{
int left;
int right;
int value;

}node[maxNode*4];
int father[maxNode];
void BuildTree( int i,int left,int right)
{
node[i].left=left;
node[i].right=right;
node[i].value=0;
if(right==left)
{
father[left]=i;
return;
}

BuildTree(i<<1,left,(int)floor((left+right)/2.0));
BuildTree((i<<1)+1,(int)floor((left+right)/2.0)+1,right);

}

void updateTree(int ri){

if(ri==1) return;
int fi = ri/2;
node[fi].value = node[fi<<1].value + node[(fi<<1)+1].value;
updateTree(fi);

}

int sum;
void Query(int i,int l,int r)
{

if(node[i].left==l && node[i].right==r)
{
    sum+=node[i].value;
    return ;
}
i=i<<1;
if(l<=node[i].right)
{
    if(r<=node[i].right)
        Query(i,l,r);
    else
        Query(i,l,node[i].right);
}
i=i+1;
if(r>=node[i].left)
{
    if(l>=node[i].left)
        Query(i,l,r);
    else
        Query(i,node[i].left,r);
}

}

int main()
{
int T;
scanf("%d",&T);
int cnt=1;
while(T--)
{
int N;
int a,b;
char str[10];
scanf("%d",&N);
BuildTree(1,1,N);
int num;

    for(int i=1;i<=N;i++)
    {
        scanf("%d",&num);
        node[father[i]].value = num;
        updateTree(father[i]);
    }
    printf("Case %d:\n",cnt++);
    while(scanf("%s",str))
    {
        if(str[0]=='E')
            break;

        scanf("%d%d",&a,&b);
        if (str[0]=='Q')
        {
            sum=0;
            Query(1,a,b);
            printf("%d\n",sum);
        }
        else if(str[0]=='A')
        {
            node[father[a]].value=node[father[a]].value+b;
            updateTree(father[a]);
        }
        else if(str[0]=='S')
         {

            node[father[a]].value=node[father[a]].value-b;
            updateTree(father[a]);
         }

    }

}
return 0;

}

posted @ 2016-04-28 14:29  vector11248  阅读(175)  评论(0编辑  收藏  举报