HDU1166 敌兵布阵
简单线段树,单点更新,区间查询,自下向上更新结点的信息~
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn=1e6+14; struct node { int l; int r; int sum; }segTree[maxn*3]; int num[maxn]; void build (int i,int l,int r) { segTree[i].l=l; segTree[i].r=r; if (l==r) { segTree[i].sum=num[l]; return; } int mid=(l+r)>>1; build (i<<1,l,mid); build (i<<1|1,mid+1,r); segTree[i].sum=segTree[i<<1].sum+segTree[i<<1|1].sum; } void add (int i,int t,int b) { segTree[i].sum+=b; if (segTree[i].l==t&&segTree[i].r==t) return; int mid=(segTree[i].l+segTree[i].r)>>1; if (t<=mid) add (i<<1,t,b); else add (i<<1|1,t,b); } int query (int i,int l,int r) { if (l==segTree[i].l&&r==segTree[i].r) return segTree[i].sum; int mid=(segTree[i].l+segTree[i].r)>>1; if (r<=mid) return query(i<<1,l,r); else if (l>mid) return query(i<<1|1,l,r); else return query(i<<1,l,mid)+query(i<<1|1,mid+1,r); } int main () { int T; int ans=0; int n; int a,b; char s[maxn]; scanf ("%d",&T); while (T--) { ans++; scanf ("%d",&n); for (int i=1;i<=n;i++) scanf ("%d",&num[i]); build (1,1,n); printf ("Case %d:\n",ans); while (scanf("%s",s)) { if (strcmp(s,"End")==0) break; scanf ("%d %d",&a,&b); if (strcmp(s,"Add")==0) add(1,a,b); else if (strcmp(s,"Sub")==0) add(1,a,-b); else printf ("%d\n",query(1,a,b)); } } return 0; }