Week3 作业 B

问题描述:

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

思路:

贪心指标:选的点尽可能覆盖更多区间;所以将区间的右端点按升序排列,按顺序取,如果当前最靠右的点能覆盖当前的区间,就继续取,否则就把最靠右的点设为当前区间的右端点;

正确性:假设当前在第i个区间,则第i+1个区间的左端点要么在r[i]的左边,要么在r[i]的右边,两种情况下上述算法得到的都不比最优解差。

代码:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 using namespace std;
 5 struct sec   //sec==section表示一段区间
 6 {
 7     int l,r;
 8     bool operator < (const sec &x) const 
 9     {
10         return r<x.r;
11     } 
12 }a[10005];
13 int main()
14 {
15     int last=-0xFFFFF,ans=0;
16     int n; cin>>n;
17     for(int i=1;i<=n;i++)
18         scanf("%d %d",&a[i].l,&a[i].r);
19     sort(a+1,a+n+1);
20     
21     for(int i=1;i<=n;i++)   //按右边界依次取区间 
22         if(a[i].l>last) ans++,last=a[i].r;
23     cout<<ans<<endl;
24 } 
25  
原文地址:https://www.cnblogs.com/qingoba/p/12426212.html