Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3484 Accepted Submission(s): 1382
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 <iostream> using namespace std; #define N 50005 #define max(a,b) a>b?a:b struct LineTree { int l,r; int max_count; LineTree *lchild,*rchild; }; int pos; LineTree mem[3*N]; int num[N]; char ch[10]; LineTree *NewTree() { LineTree *s=&mem[pos++]; return s; } LineTree *CreateTree(int a,int b) { int mid; LineTree *s=NewTree(); s->l=a; s->r=b; if(b-a>1) { mid=(a+b)/2; s->lchild=CreateTree(a,mid); s->rchild=CreateTree(mid+1,b); s->max_count=s->lchild->max_count+s->rchild->max_count; } else if(b-a==1) { s->lchild=CreateTree(a,a); s->rchild=CreateTree(b,b); s->max_count=s->lchild->max_count+s->rchild->max_count; } else s->max_count=num[s->l]; return s; } void update(LineTree *s,int a,int b) { if(s->r==s->l) { if(strcmp(ch,"Add")==0) s->max_count+=b; else s->max_count-=b; return; } if(s->lchild->r>=a) update(s->lchild,a,b); else if(s->rchild->l<=a) update(s->rchild,a,b); s->max_count=s->lchild->max_count+s->rchild->max_count; } int search(LineTree *s,int a,int b) { if(s->l==a && s->r==b) return s->max_count; int mid=(s->l+s->r)/2; if(b<=mid) return search(s->lchild,a,b); else if(mid<a) return search(s->rchild,a,b); //最初写成mid<=a,一直出错,找了好久才发现是这个错误 else { return search(s->lchild,a,mid)+search(s->rchild,mid+1,b); } } int main() { int t,n,i,flag=0; int a,b; scanf("%d",&t); while(t--) { pos=0; LineTree *s; flag++; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&num[i]); s=CreateTree(1,n); getchar(); printf("Case %d:/n",flag); while(scanf("%s",ch)) { if(strcmp(ch,"End")==0) break; scanf("%d%d",&a,&b); if(strcmp(ch,"Query")==0) { printf("%d/n",search(s,a,b)); } else update(s,a,b); } } return 0; }