标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 62044 Accepted Submission(s): 26225
#include <stdio.h> struct { int l,r,sum; }t[140000]; int r[50009],SUM; void make(int left,int right,int num)//创建线段树 { t[num].l=left; t[num].r=right; if(left==right) t[num].sum=r[left]; else { make(left,(left+right)/2,num+num); make((left+right)/2+1,right,num+num+1); t[num].sum=t[num+num].sum+t[num+num+1].sum; } } void query(int left,int right,int num)//查找范围内父节点的和 { if(left<=t[num].l&&right>=t[num].r) SUM+=t[num].sum; else { if(right<=(t[num].l+t[num].r)/2) query(left,right,num+num); else if(left>=(t[num].l+t[num].r)/2+1) query(left,right,num+num+1); else { query(left,right,num+num); query(left,right,num+num+1); } } } void add(int x,int y,int num)//修改每一个包括改变的那个数的节点 { t[num].sum+=y; if(t[num].l==t[num].r) return ; if(x>(t[num].l+t[num].r)/2) add(x,y,num+num+1); else add(x,y,num+num); } void sup(int x,int y,int num) { t[num].sum-=y; if(t[num].l==t[num].r)return ; if(x>(t[num].l+t[num].r)/2) sup(x,y,num+num+1); else sup(x,y,num+num); } int main() { int t,i,a,b,n,m=0; char s[10]; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&r[i]); make(1,n,1); printf("Case %d:\n",++m); while(1) { // scanf("%s",s); if(s[0]==‘E‘) break; if(s[0]==‘Q‘) { scanf("%d %d",&a,&b); SUM=0; query(a,b,1); printf("%d\n",SUM); } if(s[0]==‘A‘) { scanf("%d %d",&a,&b); add(a,b,1); } if(s[0]==‘S‘) { scanf("%d %d",&a,&b); sup(a,b,1); } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/zhangfengnick/p/4872043.html