标签:des style blog class code java
A - 敌兵布阵
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
Input
Output
Sample Input
Sample Output
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #define MAX 55555 using namespace std; int a[MAX*4]; void build(int l,int r,int x) //建树(在a[x]处输入一个数) { if(l==r) //区间已经到达叶子区间 { scanf("%d",&a[x]); return; } int mid=(l+r)/2; build(l,mid,x*2); build(mid+1,r,x*2+1); a[x]=a[x*2]+a[x*2+1]; } void update(int k,int num,int l,int r,int x) { if(l==r) { a[x]+=num; return; } int mid=(l+r)/2; if(k<=mid) update(k,num,l,mid,x*2); else update(k,num,mid+1,r,x*2+1); a[x]=a[x*2]+a[x*2+1]; } int getsum(int i,int j,int l,int r,int x) { if(i<=l&&j>=r) { return a[x]; } int mid=(l+r)/2; int sum=0; if(i<=mid) sum+=getsum(i,j,l,mid,x*2); if(j>mid) sum+=getsum(i,j,mid+1,r,x*2+1); return sum; } int main() { int T; int kase=1; scanf("%d",&T); while(T--) { char str[10]; printf("Case %d:\n",kase++); int n; scanf("%d",&n); build(1,n,1); while(~scanf("%s",str)) { if(str[0]==‘E‘) { break; } int a,b; scanf("%d%d",&a,&b); if(str[0]==‘A‘) update(a,b,1,n,1); else if(str[0]==‘S‘) update(a,-b,1,n,1); else if(str[0]==‘Q‘) printf("%d\n",getsum(a,b,1,n,1)); } } return 0; }
树状数组实现:
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<algorithm> #include<cstdlib> using namespace std; int c[60000]; int n; int lowbit(int x)//计算lowbit { return x&(-x); } void add(int i,int val)//将第i个元素更改为val { val+=c[i]; while(i<=n) { c[i]+=val; i+=lowbit(i); } } int sum(int i)//求前i项和 { // printf("i=%d\n",i); int s=0; while(i>0) { s+=c[i]; i-=lowbit(i); } return s; } void update(int i, int val) //更新函数 { while(i <= n) { c[i] += val; i += lowbit(i); } } int main() { int i,j,k,l; int T; char sh[15]; int kase=1; int x,y; cin>>T; while(T--) { cin>>n; memset(c,0,sizeof(c)); for(i=1;i<=n;i++) { int val; scanf("%d",&val); update(i, val); } printf("Case %d:\n",kase++); // for(i=1;i<=n;i++) // { // printf("%d ",c[i]); // } // cout<<endl; getchar(); //ok while(scanf("%s", sh)) { if(sh[0] == ‘E‘) break; scanf("%d %d", &x, &y); if(sh[0] == ‘A‘) update(x, y); else if(sh[0] == ‘S‘) update(x, -y); else printf("%d\n", sum(y)-sum(x-1)); //两段区间和相减 } } return 0; }
线段树 --- (单点更新、求区间最值、模板题),布布扣,bubuko.com
标签:des style blog class code java
原文地址:http://www.cnblogs.com/acmer-jsb/p/3705396.html