贪心算法经典例题2:区间覆盖
问题描述:
数轴上有n个区间[ai,bi],选择尽量少的区间覆盖一条指定线段[s,t],输出最少区间数和具体的区间。
思路:
将a从小到大排序,如果区间1的起点不是s,无解,否则起点在s的最长区间。选择[ai,bi]后,新的起点设置成bi。直至覆盖整个线段。
代码
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
bool comp(pair<int,int>a,pair<int,int>b)
{
return a.first<b.first;
}
int main()
{
int s,t,count;
cin>>s>>t;
int n;
cin>>n;
pair<int,int> a[n+1];
for(int i=0;i<n;i++)
{
cin>>a[i].first>>a[i].second;
}
sort(a,a+n,comp);
count=0;
int newstart=s;
int len=0,temp,maxl;
int k=0;
while(len<t-s)
{ maxl=0;
for(int i=0;i<n;i++)
{
if(a[i].first<=newstart)
{
temp=a[i].second-newstart;
if(temp>maxl)
{
maxl=temp;
k=i;
}
}
else
break;
}
if(maxl==0)
{
cout<<-1;
return 0;
}
cout<<"("<<a[k].first<<","<<a[k].second<<")"<<" ";
len=len+maxl;
newstart=a[k].second;
count++;
}
cout<<count;
}