练树状/
直接上代码了,也没其他意义.
#include <iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<vector> using namespace std; typedef struct even{int y1,y2,x;}even; #define FOR(i,s,t) for(int i=(s); i<(t); i++) #define LL long long #define BUG puts("here!!!") #define print(x) printf("%d\n",x) #define STOP system("pause") #define eps 1e-8 #define PI acos(-1.0) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define maxn 50005 LL gcd(LL a,LL b) {return a?gcd(b%a,a):b;} int A[maxn],C[maxn],n; int lowbit(int x){ return x&(-x); } void update(int pos,int num){ while(pos<=n){ C[pos]+=num; pos+=lowbit(pos); } } int Sum(int end){ int sum = 0; while(end > 0){ sum += C[end]; end-= lowbit(end); } return sum; } int main(){ int T,i,j,Cas=1; char op[10]; scanf("%d",&T); while(T--){ printf("Case %d:\n",Cas++); memset(A,0,sizeof(A)); memset(C,0,sizeof(C)); scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&A[i]); update(i,A[i]); } while(scanf("%s",op)){ if(op[0]=='E') break; scanf("%d%d",&i,&j); if(op[0]=='A') { update(i,j); } if(op[0]=='S') { update(i,-j); } if(op[0]=='Q'){ printf("%d\n",Sum(j)-Sum(i-1));//i~~j 包括i } } } return 0; }
以前写的线段树,也贴下吧
:
#include<stdio.h> #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 const int maxn=55555; int sum[maxn<<2]; void PushUp(int rt) { sum[rt]=sum[rt<<1]+sum[rt<<1|1]; } void build(int l,int r,int rt) { if(l==r) { scanf("%d",&sum[rt]); return; } int m=(l+r)>>1; build(lson); build(rson); PushUp(rt); } void update(int p,int add,int l,int r,int rt) { if(l==r){ sum[rt]+=add; return; } int m=(l+r)>>1; if(p<=m) update(p,add,lson); else update(p,add,rson); PushUp(rt); } int query(int L,int R,int l,int r,int rt) { if(L<=l&&r<=R) return sum[rt]; int m=(l+r)>>1; int ret=0; if(L<=m) ret+=query(L,R,lson); if(R>m) ret+=query(L,R,rson); return ret; } int main() { int T,Case,n; char op[10]; scanf("%d",&T); for(Case=1;Case<=T;Case++){ printf("Case %d:\n",Case); scanf("%d",&n); /* for(int i=1;i<=n;i++){ int a; scanf("%d",&a); update(i,a,1,n,1); } */ build(1,n,1); while(scanf("%s",op)) { if(op[0]=='E') break; int a,b; scanf("%d%d",&a,&b); if(op[0]=='Q') printf("%d\n",query(a,b,1,n,1)); else if(op[0]=='A') update(a,b,1,n,1); else update(a,-b,1,n,1); } } return 0; }