标签:
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
这题在之前是用线段树做的,今天艾神讲分块,把艾神的分块做法贴一下
1 //2016.8.12 2 #include<iostream> 3 #include<stdio.h> 4 #include<algorithm> 5 #include<string.h> 6 #define kuai 230 7 using namespace std; 8 int arr[50005],n; 9 int sum[305]; 10 void add(int x,int y) 11 { 12 int belong=x/kuai; 13 sum[belong]+=y; 14 arr[x]+=y; 15 return; 16 } 17 int query(int x,int y) 18 { 19 int l=0,r=kuai-1,ans=0; 20 for (int i=0;i<kuai;i++,l+=kuai,r+=kuai) 21 { 22 int L,R; 23 L=max(l,x); 24 R=min(r,y); 25 if (L>R) continue; 26 if (L==l && R==r) 27 ans+=sum[i]; 28 else 29 { 30 for (int j=L;j<=R;j++) 31 ans+=arr[j]; 32 } 33 } 34 return ans; 35 } 36 int main() 37 { 38 int t; 39 cin>>t; 40 for (int cas=1;cas<=t;cas++) 41 { 42 cin>>n; 43 for (int i=1;i<=n;i++) 44 scanf("%d",&arr[i]); 45 memset(sum,0,sizeof(sum)); 46 for (int i=1;i<=n;i++) 47 { 48 int belong=i/230; 49 sum[belong]+=arr[i]; 50 } 51 char ch[10]; 52 printf("Case %d:\n",cas); 53 scanf("%s",ch); 54 while (ch[0]!=‘E‘) 55 { 56 int x,y; 57 scanf("%d%d",&x,&y); 58 if (ch[0]==‘A‘) 59 add(x,y); 60 else 61 if (ch[0]==‘S‘) 62 add(x,-y); 63 else 64 printf("%d\n",query(x,y)); 65 scanf("%s",ch); 66 } 67 } 68 }
标签:
原文地址:http://www.cnblogs.com/Penn000/p/5766751.html