校门外的树
某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米。我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置;数轴上的每个整数点,即0,1,2,……,L,都种有一棵树。
由于马路上有一些区域要用来建地铁。这些区域用它们在数轴上的起始点和终止点表示。已知任一区域的起始点和终止点的坐标都是整数,区域之间可能有重合的部分。现在要把这些区域中的树(包括区域端点处的两棵树)移走。你的任务是计算将这些树都移走后,马路上还有多少棵树。
输入格式 |
|||
输入的第一行有两个整数L(1 <= L <= 2亿)和 M(1 <= M <= 20000),L代表马路的长度,M代表区域的数目,L和M之间用一个空格隔开。接下来的M行每行包含两个不同的整数,用一个空格隔开,表示一个区域的起始点和终止点的坐标。 |
|||
输出格式 |
|||
输出包括一行,这一行只包含一个整数,表示马路上剩余的树的数目 输入样例 500 3 150 300 100 200 470 471 输出样例 298 |
这个题有三种解法:模拟,区间合并、线段树。
第一种太白痴,略。
第三种 NOIP 不考,略。
然后讲第二种。
首先,将区间按左端点排序,然后用 last 记录当前合并到了哪里,每一次,如果下一个区间的左端点在 last 之前,但是右端点在 last 之后,就加上 右端点到 last 的距离,包含就跳过,完全不交叉就加上这个区间的长度,如果这个区间的右端点 > last 就更新 last。
代码 (SueMiller)
program ACRush;
var l,m:longint;
i,j,k,x,y,ans,last:longint;
a:array[0..20010,1..2]of longint;
procedure quicksort1(l,r:longint);
var x,i,j:longint;
begin
i:=l; j:=r; x:=a[(l+r)>>1,1];
repeat
while a[i,1]<x do inc(i);
while x<a[j,1] do dec(j);
if i<=j then
begin
a[0]:=a[i]; a[i]:=a[j]; a[j]:=a[0];
inc(i); dec(j);
end;
until i>j;
if l<j then quicksort1(l,j);
if i<r then quicksort1(i,r);
end;
begin
assign(input,'tree.in');reset(input);
assign(output,'tree.out');rewrite(output);
readln(l,m);
for i:=1 to m do
begin
readln(x,y);
if x>y then
begin
k:=x;x:=y;y:=k;
end;
if x<1 then x:=1;
if y>l then y:=l;
a[i,1]:=x;
a[i,2]:=y;
end;
quicksort1(1,m);
ans:=a[1,2]-a[1,1]+1;
last:=a[1,2];
for i:=2 to m do
begin
if a[i,1]<=last then
begin
if a[i,2]>last then
inc(ans,a[i,2]-last);
end
else begin
inc(ans,a[i,2]-a[i,1]+1);
end;
if a[i,2]>last then last:=a[i,2];
end;
writeln(l+1-ans);
close(input);close(output);
end.