1429:線段
時間限制: 1000 ms 內存限制: 65536 KB
提交數: 1641 通過數: 608
【題目描述】
在一個數軸上有n條線段,現選取其中k條線段使得這k條線段兩兩沒有重合部分,問最大的k爲多少?
【輸入】
第一行爲一個正整數n,下面n行每行2個數字ai,bi,描述每條線段。
【輸出】
輸出文件僅包括1個整數,爲k的最大值。
【輸入樣例】
3
0 2
2 4
1 3
【輸出樣例】
2
【提示】
【數據規模】
對於20%的數據,n≤10。
對於50%的數據,n≤1000。
對於70%的數據,n≤100000。
對於20%的數據,n≤1000000,0≤ai<bi≤1000000。
思路:用貪心,如果後面一個線段頭line[i].x 大於前面一個線路的尾tmp就不存在重疊,符合條件,再將前面這個尾更新爲後面新的尾,計數+1.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1000000+5;
using namespace std;
struct node{
int x;
int y;
bool operator < (const node &r)const{//重載比較操作符
return y < r.y;
}
}line[N];
int main(){
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d%d",&line[i].x,&line[i].y);
sort(line+1,line+1+n);//排序
int res = 1;//初始化
int tmp = line[1].y;//第一個賦值給tmp
for(int i = 2; i <= n; i++)//第二個開始比較
{
if(line[i].x >= tmp)
{
tmp = line[i].y;
res++;
}
}
printf("%d\n",res);
return 0;
}