在一條數軸上有N個點,分別是1~N。一開始所有的點都被染成黑色。接着
我們進行M次操作,第i次操作將[Li,Ri]這些點染成白色。請輸出每個操作執行後
剩餘黑色點的個數。
輸入一行爲N和M。下面M行每行兩個數Li、Ri
輸出M行,爲每次操作後剩餘黑色點的個數。
10 3
3 3
5 7
2 8
9
6
3
數據限制
對30%的數據有1<=N<=2000,1<=M<=2000
對100%數據有1<=Li<=Ri<=N<=200000,1<=M<=200000
這道題最容易想到的就是線段樹,但是此題用並查集複雜度更低,將右邊界
作爲根節點,這樣就可以避免重複計算一個點,對於計算了的肯定合併到右邊界
上,所以直接跳就行。
#include <stdio.h>
const int maxn = 200005;
int father[maxn];
bool col[maxn];
void init ( int n )
{
for ( int i = 1; i <= n; i ++ )
father[i] = i, col[i] = false;
}
int find ( int x )
{
return x == father[x] ? x : father[x] = find ( father[x] );
}
void Merge ( int x, int y )
{
int fx = find ( x ), fy = find ( y );
if ( fx != fy )
father[fx] = fy;
}
int main ( )
{
int n, m, ans, L, R;
scanf ( "%d%d", &n, &m );
ans = n;
init ( n );
while ( m -- )
{
scanf ( "%d%d", &L, &R );
int i = L;
while ( i <= R ) //將最遠的右邊界作爲根節點
{
if ( col[i] == false )
{
col[i] = true;
ans --;
}
int t = find ( i );
Merge ( i, R );
i = t+1; //直接可以跳到右邊界+1位置,因爲前面已經計算
}
printf ( "%d\n", ans );
}
return 0;
}