线段树练习题一

来源:互联网 发布:linux posix 编辑:程序博客网 时间:2024/04/30 23:40

线段树练习题一

Time Limit:10000MS Memory Limit:65536K
Total Submit:32 Accepted:14
Case Time Limit:1000MS

Description

桌子上零散地放着若干个盒子,桌子的后方是一堵墙。如右图所示。现在从桌子的前方射来一束平行光, 把盒子的影子投射到了墙上。问影子的总宽度是多少?

Input

Output

Sample Input

20 //桌面总宽度
4 //盒子数量
1 5
3 8
7 10
13 19
Sample Output

15
Hint

数据范围
1<=n<=100000,1<=m<=100000,保证坐标范围为[1,n].
做法:线段树模板
代码如下:

const  maxn=1000000;var  c:array[0..maxn] of longint;  n,m,a,b,i,ans:longint;procedure insert(p,l,r,a,b:longint);var  m:longint;begin  if c[p]=0 then    begin      m:=(l+r) div 2;      if (a=l)and(b=r) then c[p]:=1      else if b<=m then insert(p*2,l,m,a,b)      else if a>=m then insert(p*2+1,m,r,a,b)      else begin             insert(p*2,l,m,a,m);             insert(p*2+1,m,r,m,b);           end;    end;end;function count(p,l,r:longint):longint;begin  if c[p]=1 then count:=r-l  else if r-l=1 then count:=0  else count:=count(p*2,l,(l+r) div 2)+count(p*2+1,(l+r) div 2,r);end;begin  read(n,m);  for i:=1 to m do    begin      readln(a,b);      insert(1,1,n,a,b);    end;  ans:=count(1,1,n);  writeln(ans);end.
0 0
原创粉丝点击