您的位置:首页 > 其它

hdu 1166 敌兵布阵

2014-08-08 14:47 134 查看
题目链接:点击打开链接

数据结构模板题

线段树版:

#include <iostream>
#include <cstdio>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define MAX 50010
int sum[MAX<<2];
void pushup(int rt){
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}

void build(int l,int r,int rt){
    if(l==r){
        scanf("%d",&sum[rt]);
        return ;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushup(rt);
}

void update(int p,int add,int l,int r,int rt){
    if(l==r){
        sum[rt]+=add;
        return ;
    }
    int m=(l+r)>>1;
    if(p<=m){
        update(p,add,lson);
    }
    else
        update(p,add,rson);
    pushup(rt);
}

int query(int L,int R,int l,int r,int rt){
    if(L<=l&&R>=r)
        return sum[rt];
    int m=(l+r)>>1;
    int res=0;
    if(L<=m)res+=query(L,R,lson);
    if(R>m) res+=query(L,R,rson);
    return res;
}

int main(){
    int T;
    cin>>T;
    int flag=1;
    while(T--){
            printf("Case %d:\n",flag++);
            int n;
            scanf("%d",&n);
            build(1,n,1);
            char t[20];
            scanf("%s",t);
            while(t[0]!='E'){
                int a,b;
                scanf("%d%d",&a,&b);
                if(t[0]=='Q'){
                    printf("%d\n",query(a,b,1,n,1));
                }
                else if(t[0]=='A')
                    update(a,b,1,n,1);
                else
                    update(a,-b,1,n,1);

                scanf("%s",t);
            }
    }
    return 0;
}


树状数组版:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int c[50010];

int N;
int lowbit(int n){
    return n&(-n);
}
int sum(int end){
    int res=0;
    while(end>0){
        res+=c[end];
        end-=lowbit(end);
    }
    return res;
}
void update(int pos,int add){
    while(pos<=N){
        c[pos]+=add;
        pos+=lowbit(pos);
    }
}

int main(){
    int T;
    cin>>T;
    int flag=1;
    while(T--){
        printf("Case %d:\n",flag++);
        scanf("%d",&N);
        memset(c,0,sizeof(c));
        for(int i=1;i<=N;i++){
                int t;
                scanf("%d",&t);
                update(i,t);
        }
        char k[20];
        scanf("%s",k);
        while(k[0]!='E'){
            int a,b;
            scanf("%d%d",&a,&b);
            if(k[0]=='Q'){
                printf("%d\n",sum(b)-sum(a-1));
            }
            else if(k[0]=='A'){
                update(a,b);
            }
            else update(a,-b);
            scanf("%s",k);
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: