标签:
Description
Input
Output
Sample Input
Sample Output
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAX = 55555; int sum[MAX << 2], a[MAX]; void build(int n, int l,int r) { if( l == r){ sum[n] = a[l]; return ; } int mid = ( l + r) >> 1; build(n << 1, l, mid); build(n << 1|1, mid + 1, r); sum[n] = sum[n << 1] + sum[n << 1|1]; } int query(int n, int l, int r, int begin, int end) { if(begin <= l && end >= r) return sum[n]; int ans = 0; int mid = ( l + r ) >> 1; if(begin <= mid){ ans += query(n<<1, l ,mid ,begin, end); } if( end > mid){ ans += query(n << 1|1, mid + 1, r, begin ,end); } return ans; } void update(int n, int l, int r, int x, int v) { if( l == r){ sum[n] += v; return ; } int mid = ( l + r) >> 1; if(x <= mid) update(n << 1, l, mid, x, v); else update(n << 1|1, mid + 1, r, x, v); sum[n] = sum[n << 1] + sum[n << 1|1]; } int main() { char temp[10], T, n, count = 1; int v, x, begin, end; scanf("%d",&T); while(T--){ scanf("%d",&n); for(int i = 1; i <= n ; i++) scanf("%d", &a[i]); build(1,1,n); printf("Case %d:\n", count); while(scanf("%s",temp)!= NULL){ if(strcmp(temp, "End") == 0) break; switch(temp[0]){ case‘Q‘ : scanf("%d%d",&begin,&end); printf("%d\n",query(1,1,n, begin,end));break; case‘A‘ : scanf("%d%d",&x,&v); update(1, 1, n, x, v);break; case‘S‘ : scanf("%d%d",&x,&v); update(1, 1, n, x, -v);break; } } } return 0; }
线段树的空间约为原来的四倍,但是速度更快
标签:
原文地址:http://www.cnblogs.com/zero-begin/p/4328280.html