hdu 1166 线段树 单点更新 区间查询
很久没写线段树了,这段时间打算刷个线段树专题。这道题应该算是线段树的模版题了。
1 #include<iostream> 2 #define MAX_N 50005 3 4 using namespace std; 5 6 struct node 7 { 8 int peo; 9 int l,r; 10 }num[MAX_N*4]; 11 int pp[MAX_N]; 12 13 void built_tree(int l,int r,int count) 14 { 15 num[count].l=l; 16 num[count].r=r; 17 if(l==r) 18 { 19 num[count].peo = pp[l]; 20 return ; 21 } 22 int mid = (l+r)/2; 23 built_tree(l, mid, count*2); 24 built_tree(mid+1, r, count*2+1); 25 num[count].peo=num[count*2].peo+num[count*2+1].peo; 26 } 27 int query_peo(int l,int r,int count) 28 { 29 if(num[count].l==l && num[count].r==r) 30 return num[count].peo; 31 int mid = (num[count].l+num[count].r)/2; 32 if(r<=mid) 33 return query_peo(l,r, count*2); 34 else 35 if(l>mid) 36 return query_peo(l, r, count*2+1); 37 else 38 return query_peo(l, mid,count*2)+query_peo(mid+1, r, count*2+1); 39 } 40 41 void update_peo(int a,int b,int count) 42 { 43 if(num[count].l==num[count].r && num[count].l==a) 44 { 45 num[count].peo+=b; 46 return ; 47 } 48 int mid = (num[count].l+num[count].r)/2; 49 if(a<=mid) 50 update_peo(a, b, count*2); 51 else 52 if(a>mid) 53 update_peo(a, b, count*2+1); 54 num[count].peo=num[count*2].peo+num[count*2+1].peo; 55 } 56 int main() 57 { 58 cin.sync_with_stdio(false); 59 int t,con=1; 60 cin>>t; 61 while(t--) 62 { 63 int n; 64 cin>>n; 65 for(int i = 1; i <= n; i++) 66 { 67 cin>>pp[i]; 68 } 69 built_tree(1, n, 1); 70 string s; 71 int a,b; 72 cout<<"Case "<<con++<<":"<<endl; 73 while(1) 74 { 75 cin>>s; 76 if(s=="End") 77 break; 78 cin>>a>>b; 79 if(s=="Query") 80 { 81 cout<<query_peo(a, b, 1)<<endl; 82 } 83 else 84 if(s=="Add") 85 { 86 update_peo(a, b, 1); 87 } 88 else 89 if(s=="Sub") 90 { 91 b*=-1; 92 update_peo(a, b, 1); 93 } 94 } 95 } 96 return 0; 97 }