hdu 1166(线段树or树状数组)

来源:互联网 发布:蜘蛛侠英雄归来 知乎 编辑:程序博客网 时间:2024/06/04 19:02

线段树代码:

#include <iostream>#include <stdio.h>#include <string.h>using namespace std;int n,x,y,a,num,ans;struct node{    int l,r,w,f;}tree[4*50000+1];void build(int l,int r,int k){    tree[k].l=l,tree[k].r=r;    if(l==r)    {        scanf("%d",&tree[k].w);        return ;    }    int m=(l+r)/2;    build(l,m,k*2);    build(m+1,r,k*2+1);    tree[k].w=tree[k*2].w+tree[k*2+1].w;}void sum(int k){    if(tree[k].r<=y&&tree[k].l>=x)    {        ans+=tree[k].w;        return ;    }    int m=(tree[k].r+tree[k].l)/2;    if(m>=x)sum(k*2);    if(m<y)sum(k*2+1);}void add(int k){   // cout<<"_________1"<<endl;    if(tree[k].r==tree[k].l)    {        tree[k].w+=num;        return ;    }   // cout<<"_________2"<<endl;    int m=(tree[k].r+tree[k].l)/2;    if(a<=m)add(k*2);    else add(k*2+1);    tree[k].w=tree[k*2].w+tree[k*2+1].w;}int main(){    int t,kase=1;    //freopen("cin.txt","r",stdin);    cin>>t;    while(t--)    {        cin>>n;        build(1,n,1);        char s[15];        cout<<"Case "<<kase++<<":"<<endl;        while(~scanf("%s",s))        {            if(s[0]=='Q')            {                ans=0;                scanf("%d%d",&x,&y);                sum(1);                cout<<ans<<endl;            }            if(s[0]=='A')            {                scanf("%d%d",&a,&num);                add(1);            }            if(s[0]=='S')            {                scanf("%d%d",&a,&num);                num=-num;                add(1);            }            if(s[0]=='E')                break;        }    }}

树状数组代码:

#include <iostream>#include <stdio.h>#include <string.h>using namespace std;int c[50005];int lowbit(int k){    return k&(-k);}void add(int k,int val){    while(k<=50000)    {        c[k]+=val;        k+=lowbit(k);    }}int getsum(int k){    int sum=0;    while(k)    {        sum+=c[k];        k-=lowbit(k);    }    return sum;}int main(){    int t,kase=1;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%d",&n);        memset(c,0,sizeof(c));        for(int i=1;i<=n;i++)        {            int val;            scanf("%d",&val);            add(i,val);        }        char ord[10];        printf("Case %d:\n",kase++);        while(~scanf("%s",ord))        {            if(ord[0]=='E')break;            if(ord[0]=='A')            {                int a,b;                scanf("%d%d",&a,&b);                add(a,b);            }            if(ord[0]=='S')            {                int a,b;                scanf("%d%d",&a,&b);                add(a,-b);            }            if(ord[0]=='Q')            {                int a,b;                scanf("%d%d",&a,&b);              //  cout<<"a= "<<a<<" b="<<b<<endl;             //   cout<<getsum(b)<<" "<<getsum(a)<<endl;                printf("%d\n",getsum(b)-getsum(a-1));            }        }    }}