您的位置:首页 > 产品设计 > UI/UE

hdu1166依旧是大山跑线段树题

2012-06-03 21:42 211 查看
也是不知不觉就会re 还不知道为什么 神经病题!害我做了这么长时间!!!

[align=left]Sample Input[/align]

1
10
1 2 3 4 5 6 7 8 9 10
Query 1 3
Add 3 6
Query 2 7
Sub 10 2
Add 6 3
Query 3 10
End

 

[align=left]Sample Output[/align]

Case 1:
6
33
59

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 50001
int data[maxn];
int sum,n;
struct Tree
{
int l,r;
long long sum;
}tree[3*maxn];
void build(int l,int r,int pos)
{
tree[pos].l=l;
tree[pos].r=r;
if(l==r)
{
tree[pos].sum=data[l];
return;
}
int mid=(l+r)>>1;
build(l,mid,2*pos);
build(mid+1,r,2*pos+1);
tree[pos].sum=tree[pos*2].sum+tree[pos*2+1].sum;
}
void Update(int pos,int a,int b)
{
if(tree[pos].l==a&&tree[pos].r==a)
{
tree[pos].sum+=b;
return;
}
int mid=(tree[pos].l+tree[pos].r)>>1;
if(a<=mid)
Update(pos*2,a,b);
if(a>mid)
Update(pos*2+1,a,b);
tree[pos].sum+=b;
}
void Search(int pos,int a,int b)
{
if(tree[pos].l==a&&tree[pos].r==b)
{
sum+=tree[pos].sum;
return;
}
int mid=(tree[pos].l+tree[pos].r)>>1;
if(b<=mid)
{
Search(pos*2,a,b);
}
else if(a>=mid+1)
{
Search(pos*2+1,a,b);
}
else
{
Search(pos*2,a,mid);
Search(pos*2+1,mid+1,b);
}
}
int main()
{
int t,i,a,b,ans=0;
string str;
cin>>t;
while(t--)
{
ans++;
printf("Case %d:\n",ans);
cin>>n;
data[0]=0;
for(i=1;i<=n;i++)
scanf("%d",&data[i]);
build(1,10,1);
while(1){
cin>>str;
getchar();
if(str=="End")   break;
if(str=="Add")
{
scanf("%d%d",&a,&b);
Update(1,a,b);
}
if(str=="Sub")
{
scanf("%d%d",&a,&b);
Update(1,a,-b);
}
if(str=="Query")
{
scanf("%d%d",&a,&b);
sum=0;
Search(1,a,b);
printf("%d\n",sum);
}
}
}
return 0;
}


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