标签:
Description
Input
Output
Sample Input
1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Sample Output
Case 1: 6 33 59
终于线段树版本的,改了一上午的模板233333,心累......
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 #define M 50050 5 struct segtree 6 { 7 int l,r,sum; 8 int mid() 9 { 10 return (l+r)/2; 11 } 12 }tree[M*4]; 13 int n,t,ans,cnt=0; 14 void buildTree (int now,int left,int right) 15 { 16 tree[now].l=left; 17 tree[now].r=right; 18 if (left==right) 19 { 20 scanf("%d",&tree[now].sum); 21 return ; 22 } 23 int middle=tree[now].mid(); 24 buildTree(now<<1,left,middle); 25 buildTree(now<<1|1,middle+1,right); 26 tree[now].sum=tree[now<<1].sum+tree[now<<1|1].sum; 27 } 28 void update (int now,int left,int right,int x,int change) 29 { 30 if (left==right) 31 { 32 tree[now].sum+=change; 33 return ; 34 } 35 int middle=tree[now].mid(); 36 int lch=now*2,rch=now*2+1; 37 if (x<=middle) 38 update(lch,left,middle,x,change); 39 else 40 update(rch,middle+1,right,x,change); 41 tree[now].sum=tree[lch].sum+tree[rch].sum; 42 } 43 void query(int now,int left,int right,int L,int R)//L,R是查询的区间 44 //now是当前节点的数组下标,left,right分别是其区间的左右边界 45 { 46 if (L<=left&&right<=R)//这个区间包括在查询区间内 47 { 48 ans+=tree[now].sum; 49 return ; 50 } 51 int middle=tree[now].mid(); 52 if (R<=middle)// 这个区间在查询区间的左半部分 53 query(now<<1,left,middle,L,R); 54 else if (L>middle)// 这个区间在查询区间的右半部分 55 query(now<<1|1,middle+1,right,L,R); 56 else//这个区间在查询区间的左右部分各有一部分 57 // ========|======== 58 // ******** 59 { 60 query(now<<1,left,middle,L,R); 61 query(now<<1|1,middle+1,right,L,R); 62 } 63 } 64 int main() 65 { 66 //freopen("de.txt","r",stdin); 67 scanf("%d",&t); 68 while (t--) 69 { 70 printf("Case %d:\n",++cnt); 71 scanf("%d",&n); 72 buildTree(1,1,n); 73 char option[10]; 74 while (scanf("%s",option)) 75 { 76 if (option[0]==‘E‘) 77 break; 78 if (option[0]==‘Q‘) 79 { 80 int x,y; 81 ans=0; 82 scanf("%d%d",&x,&y); 83 query(1,1,n,x,y); 84 printf("%d\n",ans); 85 } 86 else if (option[0]==‘A‘) 87 { 88 int x,y; 89 scanf("%d%d",&x,&y); 90 update(1,1,n,x,y); 91 } 92 else 93 { 94 int x,y; 95 scanf("%d%d",&x,&y); 96 update(1,1,n,x,-y); 97 } 98 } 99 100 } 101 return 0; 102 }
标签:
原文地址:http://www.cnblogs.com/agenthtb/p/5874578.html