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
Case 1: 6 33 59
很简单的线段树。主要是很久没有研究过数据结构了,想找一道来练练手
其实用树状数组也可以实现,而且代码量也要少很多
我的代码:
#include<stdio.h> #include<string.h> #define maxn 50000 struct node { int left; int right; int sum; }; node tree[3*maxn]; int a[maxn+5]; void build(int left,int right,int root) { tree[root].left=left; tree[root].right=right; if(left==right) { tree[root].sum=a[left]; return; } int mid=(left+right)>>1; build(left,mid,root*2); build(mid+1,right,root*2+1); tree[root].sum=tree[root*2].sum+tree[root*2+1].sum; } int search(int left,int right,int root) { if(tree[root].left==left&&tree[root].right==right) { return tree[root].sum; } int mid=(tree[root].left+tree[root].right)>>1; if(right<=mid) return search(left,right,root*2); else if(left>mid) return search(left,right,root*2+1); else return search(left,mid,root*2)+search(mid+1,right,root*2+1); } void swap(int &x,int &y) { int temp; temp=x; x=y; y=temp; } void ADD(int root,int x,int y) { if(tree[root].left==x&&tree[root].right==x) { tree[root].sum=tree[root].sum+y; root=(root>>1); while(root) { tree[root].sum=tree[root].sum+y; root=(root>>1); } return; } int mid=(tree[root].left+tree[root].right)>>1; if(x<=mid) ADD(root*2,x,y); else ADD(root*2+1,x,y); } void SUB(int root,int x,int y) { if(tree[root].left==x&&tree[root].right==x) { tree[root].sum=tree[root].sum-y; root=(root>>1); while(root) { tree[root].sum=tree[root].sum-y; root=(root>>1); } return; } int mid=(tree[root].left+tree[root].right)>>1; if(x<=mid) SUB(root*2,x,y); else SUB(root*2+1,x,y); } int main() { int i,t,A,B,s,n,T; char control[10]; scanf("%d",&T); for(t=1;t<=T;t++) { scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&a[i]); build(1,n,1); printf("Case %d:\n",t); while(true) { scanf("%s",control); if(strcmp(control,"End")==0) break; if(strcmp(control,"Query")==0) { scanf("%d%d",&A,&B); if(A>B) swap(A,B); s=search(A,B,1); printf("%d\n",s); } if(strcmp(control,"Add")==0) { scanf("%d%d",&A,&B); ADD(1,A,B); } if(strcmp(control,"Sub")==0) { scanf("%d%d",&A,&B); SUB(1,A,B); } } } return 0; }