贪心算法经典例题2:区间覆盖

贪心算法经典例题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;
	
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值