标签:ons mem cep desc scan uil add 数据 线段
题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1166
题目:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 92175 Accepted Submission(s): 38840
1 #include <cstdio> 2 #include <cstring> 3 const int N=50000*4+5; 4 struct node{ 5 int l,r; 6 int sum; 7 }tree[N]; 8 int a[50005]; 9 int n; 10 void build(int bg,int ed,int i){//建树 11 if(i>4*n) return ;//记得设返回条件(4*n个节点足以),否则会无限制建下去 12 tree[i].l=bg; 13 tree[i].r=ed; 14 if(bg==ed) tree[i].sum=a[bg];//找到叶子节点 15 else{ 16 build(bg, (bg+ed)/2, i*2);//建左节点 17 build((bg+ed)/2+1, ed, i*2+1);//建右节点 18 tree[i].sum=tree[2*i].sum+tree[2*i+1].sum;//区间总值 19 } 20 } 21 void update(int i,int x,int y){//更新 22 if(tree[i].l==tree[i].r) tree[i].sum+=y; 23 else{ 24 int mid=(tree[i].l+tree[i].r)/2; 25 if(x<=mid) update(2*i, x, y); 26 else update(2*i+1, x, y); 27 tree[i].sum=tree[2*i].sum+tree[2*i+1].sum;//回溯更新父节点 28 } 29 } 30 int query(int bg,int ed,int i){ 31 if(tree[i].l==bg && tree[i].r==ed) return tree[i].sum;//找到完全匹配的节点 32 else{ 33 int mid=(tree[i].l+tree[i].r)/2; 34 if(ed<=mid) return query(bg, ed, 2*i);//查询区间在左子树中 35 else if(bg>mid) return query(bg, ed, 2*i+1);//查询区间在右子树种 36 else if(bg<=mid && ed>mid) return query(bg, mid, 2*i)+query(mid+1, ed, 2*i+1);//查询区间左右子树皆含有 37 } 38 return -1; 39 } 40 int main(){ 41 int t,x,y; 42 char op[10]; 43 scanf("%d",&t); 44 for (int i=1; i<=t; i++){ 45 printf("Case %d:\n",i); 46 scanf("%d",&n); 47 for (int j=1; j<=n; j++) scanf("%d",&a[j]); 48 build(1, n, 1); 49 while(scanf("%s",op)!=EOF && strcmp(op,"End")!=0){ 50 scanf("%d%d",&x,&y); 51 if(!strcmp(op, "Add")) update(1,x,y); 52 else if(!strcmp(op, "Sub")) update(1,x,-y); 53 else if(!strcmp(op, "Query")) printf("%d\n",query(x,y,1)); 54 } 55 56 } 57 return 0; 58 }
标签:ons mem cep desc scan uil add 数据 线段
原文地址:http://www.cnblogs.com/uniles/p/7160023.html