Left son of line segment tree node [A, (A+B)/2] right son [(a+b)/2,b]
This is important.
The line tree as a complete binary tree calculation, open to 3*n, but it is best to 4*n
#include <bits/stdc++.h>using namespace std;int a[50005];struct {int sum; int left,right;} b[50005*4];void Build (int left,int right,int i) {int mid; B[i].left=left;b[i].right=right; if (left==right) {b[i].sum=a[left]; return; } mid = (left+right)/2; Build (Left,mid,2*i); Build (mid+1,right,2*i+1); B[i].sum=b[2*i].sum+b[2*i+1].sum;} int Query (int left,int right,int i) {int mid; if (b[i].left==left&&b[i].right==right) return b[i].sum; Mid= (B[i].left + b[i].right)/2; if (right <= mid) return Query (left,right,2*i); else if (Left > Mid) return Query (left,right,2*i+1); else return query (left,mid,2*i) + query (mid+1,right,2*i+1);} void Add (int id,int num,int i) {if (B[i].left = = b[i].right) {b[i].sum = b[i].sum + num; return; } else {b[i].sum = b[i].sum + num; if (id<=b[i*2].right) Add (id,num,2*i); else Add (id,num,2*i+1); }}int Main () {int t,kase=1; scanf ("%d", &t); while (t--) {memset (b,0,sizeof (b)); int n; scanf ("%d", &n); for (int i=1;i<=n;i++) scanf ("%d", &a[i]); Build (1,n,1); String S;int x, y; printf ("Case%d:\n", kase++); while (Cin>>s) {if (s[0]== ' E ') is break; scanf ("%d%d", &x,&y); if (s[0]== ' Q ') {printf ("%d\n", Query (x,y,1)); } if (s[0]== ' A ') {Add (x,y,1); } if (s[0]== ' s ') Add (x,-y,1); } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Segment Tree hdu1166