B - 区间选点(Week3作业)

题目描述:

数轴上有 n 个闭区间 [a_i, b_i]。取尽量少的点,使得每个区间内都至少有一个点(不同区间内含的点可以是同一个)Input第一行1个整数N(N<=100)

第2~N+1行,每行两个整数a,b(a,b<=100)Output一个整数,代表选点的数目Examples

Input

2
1 5
4 6

Output

1

Input

3
1 3
2 5
4 6

Output

2

题目思路:

这道题可以利用贪心算法求解,首先对于小区间我们先根据区间的右端点进行排序,从小到大一次遍历区间数组,每次拿出当前的区间,利用temp记录上个区间的左端点,如果当前区间的右端点比左端点小,则说明当前区间与上个区间有重合部分,ans不做操作,反之,说明当前区间与上个区间没有重合需要增加点,ans++,并更新temp值,进行下一个区间的判断。

代码实现:

#include<bits/stdc++.h>
using namespace std;
struct e
{
 int l,r;
 operator<(const e&p)const{
  return r!=p.r ? r<p.r:p.l<l;
 }
};
int main()
{
 int n,ans=0;
 vector<e> term;
 int ll,rr;
 cin>>n;
 for(int i=0;i<n;i++)
 {
  cin>>ll>>rr;
  e node;
  node.r=rr;
  node.l=ll;
  term.push_back(node);
 }
 sort(term.begin(),term.end());
 int temp=term[0].r;
 ans=1;
 for(int i=1;i<term.size();i++)
 {
  if(temp<term[i].l)
  {
   ans++;
   temp=term[i].r;
  }
 }
 cout<<ans;
 return 0;
}
发布了24 篇原创文章 · 获赞 9 · 访问量 7174

猜你喜欢

转载自blog.csdn.net/qq_40103496/article/details/104829283