敌兵布阵 HDU 1166

题意:有N个工兵营地,每个营地都有一定的人数,对于这些营地有如下操作:

      1.询问从一个营地到另一个营地一共有多少人

      2.在某个营地添加一定数量的人

      3.在某个人营地减少一定的人。

 

题解:线段树的基本应用。

 

AC代码(可作模版):

 

 1 #include<cstdio>
 2 #include<iostream>
 3 using namespace std;
 4 
 5 const int maxn=50005;
 6 int spt[maxn*3];
 7 int T,n,cas=0;
 8 char s[10];
 9 void build(int l,int r,int pos){
10     if(l==r){
11         scanf("%d",&spt[pos]);
12         return ;
13     }
14     int mid=(l+r)>>1;
15     build(l,mid,pos*2);
16     build(mid+1,r,pos*2+1);
17     spt[pos]=spt[pos*2]+spt[pos*2+1];
18 }
19 
20 void updata(int camp,int val,int l,int r,int pos){
21     if(l==r){
22         spt[pos]+=val;
23         return;
24     }
25     int mid=(l+r)>>1;
26     if(camp<=mid) updata(camp,val,l,mid,pos*2);
27     else          updata(camp,val,mid+1,r,pos*2+1);
28     spt[pos]=spt[pos*2]+spt[pos*2+1];
29 }
30 
31 int query(int left,int right,int l,int r,int pos){
32     if(l<=left&&right<=r) return spt[pos];
33     int mid=(left+right)>>1;
34     if(r<=mid) return query(left,mid,l,r,pos*2);
35     else if(mid<l) return query(mid+1,right,l,r,pos*2+1);
36     else{
37         int lsum=query(left,mid,l,r,pos*2);
38         int rsum=query(mid+1,right,l,r,pos*2+1);
39         return lsum+rsum;
40     }
41 }
42 
43 int main()
44 {
45     scanf("%d",&T);
46     while(T--){
47         scanf("%d",&n);
48         build(1,n,1);
49         printf("Case %d:\n",++cas);
50         while(scanf("%s",s),s[0]!='E'){
51             int a,b;
52             scanf("%d %d",&a,&b);
53             if(s[0]=='Q') printf("%d\n",query(1,n,a,b,1));
54             else if(s[0]=='A') updata(a,b,1,n,1);
55             else updata(a,-b,1,n,1);
56         }
57     }
58     return 0;
59 }

 

 

 

 

 

posted on 2012-09-28 19:58  Acmer_Roney  阅读(172)  评论(0编辑  收藏  举报

导航