您的位置:首页 > 其它

线段树模板 hdu1166

2014-09-17 12:45 239 查看
#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<math.h>

#include<iostream>

#include<algorithm>

using namespace std;

#define maxn 1500000

struct ele

{

int Left;

int Right;

int Sum;

}p[maxn];

int a[maxn];

void build(int L,int R,int step)

{

p[step].Left=L;

p[step].Right=R;

if(p[step].Left==p[step].Right)

p[step].Sum=a[L];

else

{

int Mid=(p[step].Left+p[step].Right)/2;

build(L,Mid,2*step);

build(Mid+1,R,2*step+1);

p[step].Sum=p[2*step].Sum+p[2*step+1].Sum;

}

}

void update(int x,int y,int step)

{

if(p[step].Left==p[step].Right)

p[step].Sum+=y;

else

{

int Mid=(p[step].Left+p[step].Right)/2;

if(x<=Mid)

update(x,y,2*step);

else

update(x,y,2*step+1);

p[step].Sum=p[step*2].Sum+p[step*2+1].Sum;

}

}

int Sum(int L,int R,int step)

{

if(p[step].Left==L&&p[step].Right==R)

return p[step].Sum;

else

{

int Mid=(p[step].Left+p[step].Right)/2;

if(R<=Mid)

return Sum(L,R,2*step);

else

if(L>=Mid+1)

return Sum(L,R,2*step+1);

else

return Sum(L,Mid,2*step)+Sum(Mid+1,R,2*step+1);

}

}

int T;

int n;

char str[55];

int main()

{

int i;

int cnt=1;

int x,y;

scanf("%d",&T);

while(T--)

{

scanf("%d",&n);

for(i=1;i<=n;i++)

scanf("%d",&a[i]);

build(1,n,1);

printf("Case %d:\n",cnt++);

while(1)

{

scanf("%s",str);

if(str[0]=='E')

break;

scanf("%d%d",&x,&y);

if(str[0]=='Q')

printf("%d\n",Sum(x,y,1));

if(str[0]=='S')

update(x,-y,1);

if(str[0]=='A')

update(x,y,1);

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: