码迷,mamicode.com
首页 > 其他好文 > 详细

CODEVS1082 线段树练习3

时间:2015-01-06 21:17:59      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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

 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 begin
11     tree[i].val:=tree[i*2].val+tree[i*2+1].val;
12 end;
13 procedure pushdown(i:longint);
14 var len:longint;
15 begin
16     len:=tree[i].r-tree[i].l+1;
17     if tree[i].lazy<>0 then
18     begin
19         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 begin
29     tree[i].l:=l;
30     tree[i].r:=r;
31     if l=r then
32     begin
33         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 begin
45     if (l<=tree[i].l) and (tree[i].r<=r) then
46     begin
47         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 begin
61     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 begin
70     readln(n);
71     build(1,1,n);
72     readln(m);
73     for i:=1 to m do
74     begin
75         read(x);
76         if x=1 then
77         begin
78             readln(l,r,val);
79             update(1,l,r,val);
80         end else
81         begin
82             readln(l,r);
83             writeln(query(1,l,r));
84         end;
85     end;
86 end.

 

CODEVS1082 线段树练习3

标签:

原文地址:http://www.cnblogs.com/rpSebastian/p/4206966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!