基准时间限制:1 秒 空间限制:131072 KB 分值: 10
难度:2级算法题
X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。
例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重叠。
Input
第1行:1个数N,线段的数量(2 <= N <= 10000) 第2 - N + 1行:每行2个数,线段的起点和终点(-10^9 <= S,E <= 10^9)
Output
输出最多可以选择的线段数量。
Input示例
3 1 5 2 3 3 6
Output示例
2
对线段的右端进行排列,然后贪心查找就可以了,很水。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 1e4 + 5;
struct line
{
int x, y;
} L[MAXN];
bool cmp(line a, line b)
{
return a.y < b.y;
}
int main(int argc, const char * argv[])
{
// freopen("input.txt", "r", stdin);
int N;
cin >> N;
for (int i = 1; i <= N; i++)
{
scanf("%d %d", &L[i].x, &L[i].y);
}
sort(L + 1, L + N, cmp);
int res = 1;
int flagY = L[1].y;
for (int i = 2; i <= N; i++)
{
if (L[i].x >= flagY)
{
flagY = L[i].y;
res++;
}
}
cout << res << '\n';
return 0;
}