HDU 1166 敌兵布阵
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<string> 6 using namespace std; 7 #define MAXN 101000 8 #define MAXT MAXN*4 9 #define lch now<<1 10 #define rch ((now<<1)+1) 11 #define smid ((l+r)>>1) 12 int a[MAXN]; 13 struct sgt_node 14 { 15 int sum; 16 int l,r; 17 }sgt[MAXT]; 18 19 void Build_sgt(int now,int l,int r) 20 { 21 sgt[now].l=l; 22 sgt[now].r=r; 23 if (l==r) 24 { 25 sgt[now].sum=a[l]; 26 return ; 27 } 28 Build_sgt(lch,l,smid); 29 Build_sgt(rch,smid+1,r); 30 sgt[now].sum=sgt[lch].sum+sgt[rch].sum; 31 } 32 void Modify_sgt(int now,int pos,int l,int r,int v) 33 { 34 if (l==r) 35 { 36 sgt[now].sum+=v; 37 return ; 38 } 39 if (pos<=smid) 40 Modify_sgt(lch,pos,l,smid,v); 41 else 42 Modify_sgt(rch,pos,smid+1,r,v); 43 sgt[now].sum=sgt[lch].sum+sgt[rch].sum; 44 } 45 int Query_sgt(int now,int l,int r,int x,int y) 46 { 47 if (l==x && r==y) 48 return sgt[now].sum; 49 if (y<=smid) 50 return Query_sgt(lch,l,smid,x,y); 51 else if (smid<x) 52 return Query_sgt(rch,smid+1,r,x,y); 53 else 54 return Query_sgt(lch,l,smid,x,smid) 55 +Query_sgt(rch,smid+1,r,smid+1,y); 56 } 57 58 int main() 59 { 60 int n,m; 61 int nn; 62 int pid=0; 63 scanf("%d",&nn); 64 while (nn--) 65 { 66 printf("Case %d:\n",++pid); 67 scanf("%d",&n); 68 for (int i=1;i<=n;i++) 69 scanf("%d",&a[i]); 70 Build_sgt(1,1,n); 71 int opt; 72 while (true) 73 { 74 string str; 75 cin>>str; 76 if (str=="Add")//Modify 77 { 78 int pos,v; 79 scanf("%d%d",&pos,&v); 80 Modify_sgt(1,pos,1,n,v); 81 }else if (str=="Sub") 82 { 83 int pos,v; 84 scanf("%d%d",&pos,&v); 85 Modify_sgt(1,pos,1,n,-v); 86 }else if (str=="Query") 87 { 88 int x,y; 89 scanf("%d%d",&x,&y); 90 printf("%d\n",Query_sgt(1,1,n,x,y)); 91 }else break; 92 } 93 } 94 return 0; 95 }