您的位置:首页 > 其它

hdu(1166)敌兵布阵

2014-03-13 14:14 323 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1166
这题可以用树状数组来做,也可以用线段树来做.

树状数组:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAX 50005
using namespace std;
char str[4][6] ={"Query","Add","Sub","End"};
char st[6];
int a[MAX],c[MAX];
int t,n;
int lowbit(int x){
return x&(-x);
}
void add(int i,int val){
while(i <= n){
c[i] +=val;
i += lowbit(i);
}
}
int sum(int i){
int s = 0;
while(i > 0){
s += c[i];
i -= lowbit(i);
}
return s;
}
int main(){
int i;
scanf("%d",&t);
int cont = 1;
while(t--){
memset(a, 0,sizeof(a));
memset(c, 0,sizeof(c));
scanf("%d",&n);
for(i =1;i <=n;i++){
scanf("%d",a+i);
for(int j=i;j>i-lowbit(i);j--)
c[i] += a[j];
}
//for(i = 1;i<= n;i++)
//  printf("%d ",c[i]);
printf("Case%d:\n",cont++);
while(scanf("%s",st)){
if ( !strcmp(st,str[3]))
break;
int u,v;
scanf("%d%d",&u,&v);
if ( !strcmp(st,str[1]))
add(u,v);
if ( !strcmp(st,str[2]))
add(u,-v);
if ( !strcmp(st,str[0]))
printf("%d\n",sum(v)-sum(u-1));
}
}
return 0;
}


线段树:

#include <iostream>
#include <cstdio>

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

using namespace std;
const int maxn = 50005;
int tree[maxn<<2];
char str[10];

void PushUp(int rt){
tree[rt] = tree[rt<<1]+tree[rt<<1|1];
}

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

void update(int id ,int p, int l, int r, int rt){
if (l == r){
tree[rt] += p;
return ;
}
int m = (l + r) >> 1;
if (id <= m)
update(id,p,lson);
else
update(id,p,rson);
PushUp(rt);
}
int query(int L,int R,int l,int r,int rt){
if(L <= l && r <= R){
return tree[rt];
}
int m = (l + r)>>1;
int ret = 0;
if(L <= m)
ret += query(L, R, lson);
if(R > m)
ret += query(L, R, rson);
return ret;
}

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