首页 > 代码库 > CODEVS1082 线段树练习3

CODEVS1082 线段树练习3

好久不写了,复习一下,被坑了好多次~~~

 1 type arr=record 2         l,r:longint; 3         lazy,val:int64; 4         end; 5 const maxn=200008; 6 var tree:array[0..maxn*4] of arr; 7     i,j,n,m,x,l,r:longint; 8     val:int64; 9 procedure pushup(i:longint);10 begin11     tree[i].val:=tree[i*2].val+tree[i*2+1].val;12 end;13 procedure pushdown(i:longint);14 var len:longint;15 begin16     len:=tree[i].r-tree[i].l+1;17     if tree[i].lazy<>0 then18     begin19         inc(tree[i*2].val,tree[i].lazy*(len-len div 2));//左边区间要比右边区间大20         inc(tree[i*2+1].val,tree[i].lazy*(len div 2));21         inc(tree[i*2].lazy,tree[i].lazy);22         inc(tree[i*2+1].lazy,tree[i].lazy);23         tree[i].lazy:=0;//少加这句不行24     end;25 end;26 procedure build(i,l,r:longint);27 var mid:longint;28 begin29     tree[i].l:=l;30     tree[i].r:=r;31     if l=r then32     begin33         read(tree[i].val);34         tree[i].lazy:=0;35         exit;36     end;37     mid:=(l+r) div 2;38     build(i*2,l,mid);39     build(i*2+1,mid+1,r);40     pushup(i);41 end;42 procedure update(i,l,r,val:longint);43 var mid:longint;44 begin45     if (l<=tree[i].l) and (tree[i].r<=r) then46     begin47         inc(tree[i].val,val*(tree[i].r-tree[i].l+1));48         inc(tree[i].lazy,val);49         exit;50     end;51     pushdown(i);52     mid:=(tree[i].l+tree[i].r) div 2;53     if l<=mid then update(i*2,l,r,val);54     if mid<r  then update(i*2+1,l,r,val);55     pushup(i);56 end;57 function query(i,l,r:longint):int64;//数组开int64后,这里忘开了58 var mid:longint;59     sum:int64;60 begin61     if (l<=tree[i].l) and (tree[i].r<=r) then exit(tree[i].val);62     pushdown(i);63     mid:=(tree[i].l+tree[i].r) div 2;64     sum:=0;65     if l<=mid then sum:=sum+query(i*2,l,r);66     if mid<r  then sum:=sum+query(i*2+1,l,r);67     exit(sum);68 end;69 begin70     readln(n);71     build(1,1,n);72     readln(m);73     for i:=1 to m do74     begin75         read(x);76         if x=1 then77         begin78             readln(l,r,val);79             update(1,l,r,val);80         end else81         begin82             readln(l,r);83             writeln(query(1,l,r));84         end;85     end;86 end.

 

CODEVS1082 线段树练习3