http://poj.org/problem?id=3468 topic links, very classical application of line tree, here to review, and then write again, the code is as follows:
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intMAXN =100000+Ten;intN, Q;intA[MAXN];structsegment{intL, R; Long Longsum; intlazy;} seg[3*MAXN];voidBuildintRtintLintR) {SEG[RT].L= L; SEG[RT].R =R; Seg[rt].lazy=0; if(l==R) {Seg[rt].sum=A[l]; return ; } intCHL =2*RT, CHR =2*rt+1; intMid = (l+r)/2; Build (CHL, L, mid); Build (CHR, Mid+1, R); Seg[rt].sum= Seg[chl].sum +seg[chr].sum;}voidPush_down (intRT) { intCHL =2*RT, CHR =2*rt+1; if(seg[rt].lazy) {seg[chl].sum+= (Long Long) seg[rt].lazy* (Long Long) (seg[chl].r-seg[chl].l+1); Seg[chl].lazy+=Seg[rt].lazy; Seg[chr].sum+= (Long Long) seg[rt].lazy* (Long Long) (seg[chr].r-seg[chr].l+1); Seg[chr].lazy+=Seg[rt].lazy; Seg[rt].lazy=0; }}voidUpdateintRtintLintRintc) { if(Seg[rt].l==l && seg[rt].r==R) {Seg[rt].sum+= (Long Long) c* (r-l+1); Seg[rt].lazy+=C; return ; } push_down (RT); intMid = (SEG[RT].L+SEG[RT].R)/2; if(R <=mid) Update (2*RT, L, R, c); Else if(l>mid) Update (2*rt+1, L, R, c); Else{Update (2*RT, L, Mid, c); Update (2*rt+1, mid+1, R, c); } seg[rt].sum= seg[2*rt].sum + seg[2*rt+1].sum;}Long LongQueryintRtintLintR) { if(Seg[rt].l==l && seg[rt].r==S) { returnseg[rt].sum; } push_down (RT); intMid = (SEG[RT].L+SEG[RT].R)/2; if(R <=mid)returnQuery2*RT, L, R); Else if(L >mid)returnQuery2*rt+1, L, R); Else { Long LongV1 = Query (2*RT, L, mid); Long LongV2 = Query (2*rt+1, mid+1, R); returnV1 +v2; } seg[rt].sum= seg[2*rt].sum + seg[2*rt+1].sum;}intMain () {scanf ("%d%d", &n, &p); for(intI=1; i<=n; i++) scanf ("%d", &A[i]); Build (1,1, N); for(intI=0; i<q; i++){ Chars[6]; scanf ("%s", s); if(s[0] =='Q'){ intL, R; scanf ("%d%d", &l, &R); printf ("%lld\n", Query (1, L, R)); }Else{ intL, R, C; scanf ("%d%d%d", &l, &r, &c); Update (1, L, R, c); } } return 0;}
poj3468 segment Tree