hdu1166依旧是大山跑线段树题

来源:互联网 发布:奥格斯堡同盟 知乎 编辑:程序博客网 时间:2024/06/05 02:50

也是不知不觉就会re 还不知道为什么 神经病题!害我做了这么长时间!!!

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


 

Sample Output
Case 1:63359
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;#define maxn 50001int 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;}


 

原创粉丝点击