题目
题目大意
本题给出数轴上的多段区间,分别给出左端点和右端点,要求在数轴上选点,使得每段区间内至少有一个点,最终统计出最少需放置的点的个数。
解题思路
本题需要用贪心的思路来求解。在处理中先按每段右端点从小到大排序。之后从第一段开始,先在第一段右端点上放置一点,再开始依次往后找,当发现某一段不包含以放置的这一点时,即该段左端点位置大于第一段右端点,那么就在这一段右端点上放置一点,再以相同的步骤向后寻找,直到最后一段。整个过程中只要记录下总共放置的点数即可。
具体代码
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include<cstdlib>
#include<ctime>
#include<iomanip>
#define ll long long
#define FOR(i,a,n) for(register int i=a;i<n;i++)
#define RF(i,a,n) for(register int i=a;i>n;i--)
#define NIL -1
using namespace std;
struct node{
int l,r;
}a[105];
int ans,point;
bool cmp(node a, node b)
{
if(a.r != b.r)
{
return a.r < b.r;
}
else
{
return a.l > b.l;
}
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i].l >> a[i].r;
}
sort(a,a+n,cmp);
for(int i = 0; i < n; i++)
{
if(i == 0)
{
point = a[i].r;
ans++;
}
else
{
if(a[i].l <= point)
{
continue;
}
else
{
point = a[i].r;
ans++;
}
}
}
cout << ans;
return 0;
}