线段树模板(以求和为例)
构造
procedure make(p,l,r:longint); var mid:longint; begin a[p,1]:=l; a[p,2]:=r; a[p,3]:=0; if l=r then a[p,3]:=w[l]; if l<r then begin mid:=(l+r) div 2; make(p*2,l,mid); make(p*2+1,mid+1,r); a[p,3]:=a[p*2,3]+a[p*2+1,3]; end; end;
修改(元素)
procedure change1(p,x,num:longint); var mid:longint; begin if a[p,1]=a[p,2] then inc(a[p,3],num) else begin mid:=(a[p,1]+a[p,2]) div 2; if x<=mid then change1(p*2,x,num) else if x>mid then change1(p*2+1,x,num); a[p,3]:=a[p*2,3]+a[p*2+1,3]; end; end;
查询(区间)
function query2(p,l,r:longint):longint; var mid,ans:longint; begin if (l<=a[p,1])and(a[p,2]<=r) then exit(a[p,3]) else begin mid:=(a[p,1]+a[p,2]) div 2; ans:=0; if l<=mid then inc(ans,query2(p*2,l,r)); if r>mid then inc(ans,query2(p*2+1,l,r)); exit(ans); end; end;
原文:http://www.cnblogs.com/qtyytq/p/4645758.html