线段树经典题(3.0版)

来源:互联网 发布:淘宝好看男鞋店铺推荐 编辑:程序博客网 时间:2024/06/16 09:19

题目大意:x轴上有若干条不同线段,问某个单位区间[x,x+1]上重叠了多少条线段?

数据:             输出:3

5 20

10 19

2 9

5 13

15 17

13 19

15 16

 

分析:我们只考虑小数据,在例三的基础上加一个域count,表示区间内的重叠的线段的数量,统计即可。

 

const

 maxn=100000;

type

 treenode=record

  cover,count:longint;

end;

 

var

 tree:array [0..maxn] of treenode;

 n,ans,pl,l:longint;

procedure insert(p,l,r,a,b:longint);

 varm:longint;

begin

 m:=(l+r) div 2;

 if(a=l) and (b=r) then

 tree[p].count:=tree[p].count+1

  else begin

   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:longint):longint;

 var

 result:longint;

begin

 result:=0;

 while p>0 do

 begin

  result:=result+tree[p].count;

  p:=p div 2;

 end;

 count:=result;

end;

 

procedure find(p,l,r,a,b:longint);

 var

 m:longint;

begin

 m:=(l+r) div 2;

 if(l=a) and (r=b) then

 pl:=p

 else if m>=b then

  find(2*p,l,m,a,b)

  else if a>=m then

   find(2*p+1,m,r,a,b)

   else begin

        find(2*p,l,m,a,m);

        find(2*p+1,m,r,m,b);

        end;

end;

 

procedure main;

 vara,b,i,c:longint;

begin

 readln(n,l);

  fori:=1 to n do

   begin

    readln(a,b);

    insert(1,1,l,a,b);

   end;

 readln(a,b);

 find(1,1,l,a,b);

 writeln(count(pl));

end;

 

begin

 main;

end.

 

0 0
原创粉丝点击