标签:sam 接下来 str span 海岸线 res cin code otto
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int MAXNODE=(1<<21)-1; 4 const int MAX=1e6+10; 5 struct NODE{ 6 int value; 7 int left,right; 8 }node[MAXNODE]; 9 int father[MAX]; 10 void buildTree(int i,int left,int right){ 11 node[i].left=left; 12 node[i].right=right; 13 node[i].value=0; 14 if(left==right){ 15 father[left]=i; 16 return ; 17 } 18 buildTree(i<<1,left,(int)(floor(left+right)/2.0)); 19 buildTree((i<<1)+1,(int)(floor(left+right)/2.0)+1,right); 20 } 21 void UpdateTree(int ri,int vl){ 22 if(ri==1) { 23 node[ri].value+=vl; 24 return ; 25 } 26 node[ri].value+=vl; 27 UpdateTree(ri/2,vl); 28 } 29 int res; 30 void Query(int i,int a,int b){ 31 if(a==node[i].left&&b==node[i].right){ 32 res+=node[i].value; 33 return; 34 } 35 i=i<<1; 36 if(a<=node[i].right){ 37 if(b<=node[i].right) Query(i,a,b); 38 else Query (i,a,node[i].right); 39 } 40 if(b>=node[i+1].left){ 41 if(a>=node[i+1].left) Query(i+1,a,b); 42 else Query(i+1,node[i+1].left,b); 43 } 44 } 45 46 int main(){ 47 int t,n,m,num,a,b; 48 ios::sync_with_stdio(false); 49 while(cin>>n>>m){ 50 buildTree(1,1,n); 51 for(int i=1;i<=n;i++){ 52 cin>>num; 53 UpdateTree(father[i],num); 54 } 55 string op; 56 while(m--){ 57 cin>>op; 58 if(op[0]==‘E‘) break; 59 else if(op[0]==‘Q‘){ 60 cin>>a>>b; 61 res=0; 62 Query(1,a,b); 63 cout<<res<<endl; 64 } 65 else if(op[0]==‘S‘){ 66 cin>>a>>b; 67 UpdateTree(father[a],-b); 68 } 69 else { 70 cin>>a>>b; 71 UpdateTree(father[a],b); 72 } 73 } 74 } 75 return 0; 76 }
树状数组
1 #include <bits/stdc++.h> 2 #define lowbit(x) x&(-x) 3 using namespace std; 4 int N,c[50005]; 5 void update(int i,int value) 6 { 7 while(i<=N){ 8 c[i]+=value; 9 i+=lowbit(i); 10 } 11 } 12 int sum(int i){ 13 int sum=0; 14 while(i>0){ 15 sum+=c[i]; 16 i-=lowbit(i); 17 } 18 return sum; 19 } 20 int main(){ 21 int t,Case=0,d; 22 scanf("%d",&t); 23 while(t--){ 24 printf("Case %d:\n",++Case); 25 scanf("%d",&N); 26 memset(c,0,sizeof(c)); 27 for(int i=1;i<=N;i++){ 28 scanf("%d", &d); 29 update(i,d); 30 } 31 char command[15]; 32 int x,y; 33 while(~scanf("%s",command)&&command[0]!=‘E‘){ 34 scanf("%d%d",&x,&y); 35 if(command[0]==‘Q‘) printf("%d\n",sum(y)-sum(x-1)); //x~y的和 36 else if(command[0]==‘A‘) update(x,y); 37 else update(x,-y); //减等价于加上它的负数 38 } 39 } 40 return 0; 41 }
标签:sam 接下来 str span 海岸线 res cin code otto
原文地址:http://www.cnblogs.com/z-712/p/7323936.html