第六次训练 I题

问题链接:Problem I

问题简述:

给出若干段区间与数字M,问这些区间能否覆盖(0,M),若能,则输出最少要用到的区间数,与用到的区间。不能,则输出0.

问题分析:

区间覆盖问题,多用贪心思想便可解决。本题贪心的思路可为每次选取一个满足条件的区间长度最长的一个区间。难点在于对路径的输出。

程序说明:

先将区间的左坐标按由小到大的顺序排列,第一次选取一个区间左坐标小于或等于0的最长区间,第二次选取做坐标小于或等于第一次选取的区间的右坐标的最长区间,以此类推直至选取的区间右坐标大于或等于M。记录区间可另定义一个数组,在每次选取时,将该区间的下标存于数组中。

AC通过的C语言程序如下:

#include<iostream>
#include<cstdio>
#include<cstdlib> 
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
struct node{
	int l,r;
}coo[100005];
int ans[100005];
bool cmp(node a,node b){
	return a.l<b.l;
} 
int main(){
	std::ios::sync_with_stdio(false);
	int t;
	cin>>t;
	while(t--){
		int m;
		cin>>m;
		int cnt=0;
		while(cin>>coo[cnt].l>>coo[cnt].r){
			if(!coo[cnt].l&&!coo[cnt].r){
				break;
			}
			cnt++;
		}
		sort(coo,coo+cnt,cmp);
		int L=0,R=0,num=0;
		bool flag=1;
		while(R<m){
			int tmp=R;
			for(int i=0;i<cnt;i++){
				if(coo[i].l<=L&&coo[i].r>R){
					R=coo[i].r;
					ans[num]=i;
				}
			}
			if(tmp==R){
				flag=0;
				break;
			}
			L=coo[ans[num]].r;
			num++;
		}
		if(flag){
			cout<<num<<endl;
			for(int i=0;i<num;i++){
				cout<<coo[ans[i]].l<<" "<<coo[ans[i]].r<<endl;
			}
		}
		else{
			cout<<0<<endl;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值