线段树练习题三
Time Limit:10000MS Memory Limit:65536K
Total Submit:17 Accepted:7
Case Time Limit:1000MS
Description
给定一条长度为m的线段,有n个操作,每个操作有3个数字x,y,z表示把区间[x,y]染成颜色z,询问染完色之后,这条长度为m的线段一共有几种颜色。规定:线段的颜色可以相同。连续的相同颜色被视作一段。问x轴被分成多少段。
Input
Output
Sample Input
20 //四条,总长度为20
10 19 1
2 9 2
5 13 3
15 17 4
Sample Output
7
Hint
数据规模
N <= 10000
M <= 1000000
做法:在练习2的基础上改改就好了
代码如下:
const
maxn=500000;
var
c:array[0..maxn] of longint;
n,m,a,b,i,ans,co,re,lc,rc:longint;
bool:array[0..maxn] of longint;
procedure insert(p,l,r,a,b,f:longint);
var
m:longint;
begin
if c[p]<>f then
begin
m:=(l+r) div 2;
if (a=l)and(b=r) then c[p]:=f
else begin
if c[p]>=0 then
begin
c[p*2]:=c[p];
c[p*2+1]:=c[p];
c[p]:=-1;
end;
if b<=m then insert(p*2,l,m,a,b,f)
else if a>=m then insert(p*2+1,m,r,a,b,f)
else begin
insert(p*2,l,m,a,m,f);
insert(p*2+1,m,r,m,b,f);
end;
end;
end;
end;
function count(p,l,r:longint; var lc,rc:longint):longint;
var
tr,tl:longint;
begin
if c[p]>=0 then
begin
lc:=c[p];
rc:=c[p];
count:=1
end
else if r-l>1 then
begin
re:=count(p*2,l,(l+r) div 2,lc,tl)+count(p*2+1,(l+r) div 2,r,tr,rc);
if (tr=tl)and(tr>0) then dec(re);
count:=re;
end;
end;
begin
readln(m,n);
for i:=1 to m do
begin
readln(a,b,co);
insert(1,1,n,a,b,co);
end;
count(1,1,n,lc,rc);
writeln(re);
end.