随笔目的:方便以后对树状数组(BIT)以及基本线段树的回顾
例题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166
例题:hdu 1166
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
树状数组(BIT)代码:
1 #include "stdio.h" 2 #include "string.h" 3 #define N 50005 4 5 int n; 6 int a[N],c[N]; 7 8 int lowbit(int x){ return x&(-x); } 9 10 int Query(int x) 11 { 12 int sum = 0; 13 for(int i=x; i>0; i-=lowbit(i)) 14 sum += c[i]; 15 return sum; 16 } 17 18 int main() 19 { 20 int T; 21 int i,j,Case=1; 22 char str[10]; 23 scanf("%d",&T); 24 while(T--) 25 { 26 scanf("%d",&n); 27 memset(a,0,sizeof(a)); 28 memset(c,0,sizeof(c)); 29 for(i=1; i<=n; i++) 30 { 31 scanf("%d",&a[i]); 32 for(j=i; j<=n; j+=lowbit(j)) 33 c[j] += a[i]; 34 } 35 printf("Case %d:\n",Case++); 36 while(scanf("%s",str),strcmp(str,"End")!=0) 37 { 38 scanf("%d %d",&i,&j); 39 if(strcmp(str,"Add")==0) 40 { 41 a[i] += j; 42 for(int k=i; k<=n; k+=lowbit(k)) 43 c[k] += j; 44 } 45 else if(strcmp(str,"Sub")==0) 46 { 47 a[i] -= j; 48 for(int k=i; k<=n; k+= lowbit(k)) 49 c[k] -= j; 50 } 51 else 52 printf("%d\n",Query(j) - Query(i-1)); 53 } 54 } 55 return 0; 56 }
线段树代码:
1 #include "iostream" 2 #include "cstdio" 3 #include "cstring" 4 using namespace std; 5 #define N 50005 6 struct point 7 { 8 int l,r; 9 int sum; 10 }Tree[N*4]; 11 12 void Build(int t,int l,int r) 13 { 14 Tree[t].l = l; 15 Tree[t].r = r; 16 Tree[t].sum = 0; 17 if(Tree[t].l == Tree[t].r) 18 { 19 scanf("%d",&Tree[t].sum); 20 return ; 21 } 22 int mid = (l+r)/2; 23 Build(t<<1,l,mid); 24 Build(t<<1|1,mid+1,r); 25 Tree[t].sum = Tree[t<<1].sum + Tree[t<<1|1].sum; 26 } 27 28 void Add(int t,int l,int r) 29 { 30 if(Tree[t].l==Tree[t].r && Tree[t].l==l) 31 { 32 Tree[t].sum += r; 33 return ; 34 } 35 int mid = (Tree[t].l+Tree[t].r)/2; 36 if(l <= mid) 37 Add(t<<1,l,r); 38 else 39 Add(t<<1|1,l,r); 40 Tree[t].sum = Tree[t<<1].sum + Tree[t<<1|1].sum; 41 } 42 int Query(int t,int l,int r) 43 { 44 if(Tree[t].l==l && Tree[t].r==r) 45 { 46 return Tree[t].sum; 47 } 48 int mid = (Tree[t].l + Tree[t].r)/2; 49 if(r <= mid) 50 return Query(t<<1,l,r); 51 else if(l > mid) 52 return Query(t<<1|1,l,r); 53 else 54 return Query(t<<1,l,mid) + Query(t<<1|1,mid+1,r); 55 } 56 57 int main() 58 { 59 int T; 60 int iCase = 0; 61 scanf("%d",&T); 62 while(T--) 63 { 64 int n; 65 iCase++; 66 printf("Case %d:\n",iCase); 67 scanf("%d",&n); 68 Build(1,1,n); 69 char str[20]; 70 getchar(); 71 while(scanf("%s",str) && strcmp(str,"End")!=0) 72 { 73 int x,y; 74 scanf("%d %d",&x,&y); 75 if(strcmp(str,"Query")==0) 76 { 77 printf("%d\n",Query(1,x,y)); 78 } 79 else if(strcmp(str,"Add")==0) 80 { 81 Add(1,x,y); 82 } 83 else if(strcmp(str,"Sub")==0) 84 { 85 Add(1,x,-y); 86 87 } 88 } 89 } 90 return 0; 91 }