hdu 1166 敌兵布阵
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166;
树状数组:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 using namespace std; 6 7 const int maxn = 50050; 8 int n,T; 9 int a[maxn]; 10 int C[maxn]; 11 int lowbit(int x){ 12 return x&(-x); 13 } 14 int sum(int x){ 15 int ret = 0; 16 while(x > 0){ 17 ret += C[x]; 18 x -= lowbit(x); 19 } 20 return ret; 21 } 22 void add(int x,int d){ 23 while(x<=n){ 24 C[x] += d; 25 x += lowbit(x); 26 } 27 } 28 int main() 29 { 30 //if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);} 31 cin>>T; 32 char ch[10]; 33 for(int t=1;t<=T;t++){ 34 cin>>n; 35 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 36 memset(C,0,sizeof(C)); 37 for(int i=1;i<=n;i++){ 38 for(int j=i-lowbit(i)+1;j<=i;j++){ 39 C[i] += a[j]; 40 } 41 } 42 printf("Case %d:\n",t); 43 scanf("%s",ch); 44 while(strcmp(ch,"End")){ 45 if(!strcmp(ch,"Query")){ 46 int a,b; 47 scanf("%d%d",&a,&b); 48 int ans = sum(b) - sum(a-1); 49 printf("%d\n",ans); 50 } 51 else if(!strcmp(ch,"Add")){ 52 int a,b; 53 scanf("%d%d",&a,&b); 54 add(a,b); 55 } 56 else if(!strcmp(ch,"Sub")){ 57 int a,b; 58 scanf("%d%d",&a,&b); 59 add(a,-b); 60 } 61 scanf("%s",ch); 62 } 63 } 64 65 }
线段树:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int maxn = 50050; int tree[4*maxn]; int a[maxn]; int n,T; char ch[10]; void build(int u,int l,int r){ if(l == r){ tree[u] = a[l]; return; } int mid = (l + r)>>1; build(2*u,l,mid); build(2*u+1,mid+1,r); tree[u] = tree[2*u] + tree[2*u+1]; } void update(int u,int l,int r,int goal,int num){ if(l == r){ tree[u] += num; return; } int mid = (l+r)/2; //printf("%d %d %d\n",l,r,mid); if(goal <= mid) update(2*u,l,mid,goal,num); else update(2*u+1,mid+1,r,goal,num); tree[u] = tree[2*u] + tree[2*u+1]; //printf("tree %d %d %d %d %d\n",u,tree[u] ,2*u,tree[2*u] ,tree[2*u+1]); } int query(int u,int l,int r,int tl,int tr){ if(tl<=l && r<=tr){ return tree[u]; } int mid = (l + r)/2; if(tr <= mid) return query(2*u,l,mid,tl,tr); else if(tl > mid) return query(2*u+1,mid+1,r,tl,tr); else return query(2*u,l,mid,tl,tr)+query(2*u+1,mid+1,r,tl,tr); } int main() { //if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);} cin>>T; for(int t=1;t<=T;t++){ cin>>n; memset(tree,0,sizeof(tree)); for(int i=1;i<=n;i++) cin>>a[i]; int tl,tr; build(1,1,n); printf("Case %d:\n",t); cin>>ch; while(strcmp(ch,"End")){ if(!strcmp(ch,"Query")){ scanf("%d%d",&tl,&tr); int ans = query(1,1,n,tl,tr); printf("%d\n",ans); } else if(!strcmp(ch,"Add")){ int a,b; scanf("%d%d",&a,&b); update(1,1,n,a,b); } else if(!strcmp(ch,"Sub")){ int a,b; scanf("%d%d",&a,&b); update(1,1,n,a,-b); } scanf("%s",ch); } } return 0; }