树状数组
#include <iostream> #include <stdio.h> #include <string.h> #define MAX 50005 using namespace std; int n,c[MAX]; int lowbit(int i) { return i&(-i); } int Query(int i) { int sum=0; while(i>0) { sum+=c[i]; i-=lowbit(i); } return sum; } void update(int i,int val) { while(i<=n) { c[i]+=val; i+=lowbit(i); } } int main() { freopen("in.txt","r",stdin); int t,a; char str[10]; scanf("%d",&t); for(int tt=1;tt<=t;tt++) { memset(c,0,sizeof(c)); printf("Case %d:\n",tt); scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a); update(i,a); } while(scanf("%s",str)!=EOF&&strcmp(str,"End")!=0) { int x,y;scanf("%d%d",&x,&y); if(!strcmp(str,"Query")) { printf("%d\n",Query(y)-Query(x-1)); } if(!strcmp(str,"Add")) { update(x,y); } if(!strcmp(str,"Sub")) { update(x,-y); } } } return 0; }
线段树
#include <iostream> #include <stdio.h> #include <string.h> #define MAX 50005 using namespace std; int n,d[MAX]; struct node { int l,r,num; }tree[MAX*3]; int build(int l,int r,int id) { tree[id].l=l; tree[id].r=r; if(l==r) { return tree[id].num=d[l]; } int mid=(l+r)/2; return tree[id].num=build(l,mid,id<<1)+build(mid+1,r,id<<1|1); } int Query(int l,int r,int id) { if(l==tree[id].l&&r==tree[id].r) { return tree[id].num; } int mid=(tree[id].l+tree[id].r)/2; if(r<=mid) { return Query(l,r,id<<1); } else if(mid<l) { return Query(l,r,id<<1|1); } else return Query(l,mid,id<<1)+Query(mid+1,r,id<<1|1); } void upDate(int i,int x,int id) { tree[id].num+=x; if(tree[id].l==tree[id].r)return; int mid=(tree[id].l+tree[id].r)/2; if(i<=mid)upDate(i,x,id<<1); else upDate(i,x,id<<1|1); } int main() { //freopen("in.txt","r",stdin); int t,a; char str[10]; scanf("%d",&t); for(int tt=1;tt<=t;tt++) { printf("Case %d:\n",tt); scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&d[i]); } build(1,n,1); while(scanf("%s",str)!=EOF&&strcmp(str,"End")!=0) { int x,y;scanf("%d%d",&x,&y); if(!strcmp(str,"Query")) { printf("%d\n",Query(x,y,1)); } if(!strcmp(str,"Add")) { upDate(x,y,1); } if(!strcmp(str,"Sub")) { upDate(x,-y,1); } } } return 0; }