HDU 1166 敌兵布阵 线段树
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1166
题意:
题解:
代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 #define MS(a) memset(a,0,sizeof(a)) 5 #define MP make_pair 6 #define PB push_back 7 const int INF = 0x3f3f3f3f; 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL; 9 inline ll read(){ 10 ll x=0,f=1;char ch=getchar(); 11 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 12 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 13 return x*f; 14 } 15 ////////////////////////////////////////////////////////////////////////// 16 const int maxn = 5e4+10; 17 18 int sum[maxn<<2]; 19 20 void pushup(int rt){ 21 sum[rt] = sum[rt<<1]+sum[rt<<1|1]; 22 } 23 24 void build(int l,int r,int rt){ 25 if(l == r){ 26 sum[rt] = read(); 27 return ; 28 } 29 int mid = (l+r)/2; 30 build(l,mid,rt<<1); 31 build(mid+1,r,rt<<1|1); 32 pushup(rt); 33 } 34 35 void update(int p,int add,int l,int r,int rt){ 36 37 if(l==r){ 38 sum[rt] += add; 39 return ; 40 } 41 int mid = (l+r)/2; 42 if(p <= mid) 43 update(p,add,l,mid,rt<<1); 44 else 45 update(p,add,mid+1,r,rt<<1|1); 46 pushup(rt); 47 } 48 49 int query(int L,int R,int l,int r,int rt){ 50 if(L<=l && r<=R){ 51 return sum[rt]; 52 } 53 int mid = (l+r)/2; 54 int ans = 0; 55 if(L>mid){ 56 ans += query(L,R,mid+1,r,rt<<1|1); 57 } 58 else if(R<=mid){ 59 ans += query(L,R,l,mid,rt<<1); 60 }else{ 61 ans += query(L,R,l,mid,rt<<1) + query(L,R,mid+1,r,rt<<1|1); 62 } 63 return ans; 64 } 65 66 int main(){ 67 int T=read(); 68 for(int cas=1; cas<=T; cas++){ 69 cout << "Case " << cas << ":\n"; 70 int n = read(); 71 build(1,n,1); 72 char op[10]; 73 while(scanf("%s",op) && op[0]!='E'){ 74 int a=read(),b=read(); 75 if(op[0]=='Q') 76 cout << query(a,b,1,n,1) << endl; 77 else if(op[0]=='S') 78 update(a,-b,1,n,1); 79 else 80 update(a,b,1,n,1); 81 } 82 } 83 84 return 0; 85 }