程序设计思维与实践 Week3 作业 C-区间覆盖

题目链接:C-区间覆盖

题目描述:
数轴上有 n (1<=n<=25000)个闭区间 [ai, bi],选择尽量少的区间覆盖一条指定线段 [1, t]( 1<=t<=1,000,000)。
覆盖整点,即(1,2)+(3,4)可以覆盖(1,4)。
不可能办到输出-1

Input:
第一行:N和T
第二行至N+1行: 每一行一个闭区间。

Output:
选择的区间的数目,不可能办到输出-1

Sample Input:
3 10
1 7
3 6
6 10

Sample Output:
2

思路:
这道题同样是贪心算法的题目,首先把区间按左端点大小进行排序,然后从左往右找到右端点能够覆盖t的区间,得出总区间个数。由于题目中要求是整点覆盖,所以每对区间的左右端点并不一定是完全重合的。对于每次起始点,都是对于上一次左端点加一处理,以保证能够完成整点覆盖。

总结:
本题的迷惑性在于“整点”,即对于选择区间过程中不必选择一定有重合部分的区间,可以对起始点进行向上或着向下取整,或着直接对上一个区间的右端点进行加一处理。

代码:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
struct node{
	int a,b;
	bool operator<(const node &no)const{
        return a<no.a;
    }
};
node k[100000];
int main(){
	int n,a,b,count,length=0,start=1,end,op,ans;
	bool temp=false;
	while(scanf("%d%d",&n,&end)!=EOF){
        ans=-1000000;
		start=1;
		count=0;
		for(int i=0;i<n;i++)
		scanf("%d%d",&k[i].a,&k[i].b);
	sort(k,k+n);
	int i=0;
	while(i<n){
        int l;
        if(k[i].a>start)
            break;
		while(i<n){
		    if(k[i].a<=start){
                if(k[i].b>ans)
                    ans=k[i].b;
            }
            else{
                start=ans+1;
                break;
            }
            i++;
		}
		count++;
		if(ans>=end){
		    temp=true;
		    break;
		}
	}
	if(temp)
	printf("%d\n",count);
		else printf("-1\n");
	}
}
发布了24 篇原创文章 · 获赞 0 · 访问量 516

猜你喜欢

转载自blog.csdn.net/qq_43666020/article/details/104905119
今日推荐