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

C-区间覆盖

Description

数轴上有 n (1<=n<=25000)个闭区间 [ai, bi],选择尽量少的区间覆盖一条指定线段 [1, t]( 1<=t<=1,000,000)。
覆盖整点,即(1,2)+(3,4)可以覆盖(1,4)。
要求输入n,t 以及n个区间,输出最少的区间数。

Sample

input:
3 10
1 7
3 6
6 10

output:
2

Idea

首先确定下来是用贪心算法,仅考虑 [ 1 , t ]内的区间,按左边界从小到大排序,如果相等则按右边界从大到小排序,逐个选择符合条件的区间,选择覆盖区间最广,即右边界最大的区间忽略包含的小区间(体现了贪心算法),此时只考虑区间左边界小于最新指定线段的左边界。选择后更新指定线段的左边界,以此类推直至覆盖整个区间。循环时要注意每次循环开始时i指向的位置。

Summary

这道题做完心态略崩,前后大概重构了四五次,最后AC地也比较玄学。
基本思想就是贪心算法,遵守的准则是对于符合条件的区间选择右边界最大的。很容易少考虑情况,容易思路混乱,也不知道WA在哪儿,重新写一遍结果AC了
如果WA可以试试下面的数据:

input:
6 10
1 5
2 6
3 4
4 5
7 10
2 3
output
3

input:
1 3
1 2
output:
-1

input:
4 100
21 50
50 81
1 20
80 99
output
-1

input:
3 6
2 3
4 5
6 6
output:
-1

如果T了,则使用cin.sync_with_stdio(false)或者scanf

Codes

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;


struct time {
	int a, b;
}tim[25001];
bool compare(time &x,time &y){
	if(x.a!=y.a)return x.a < y.a;
	else return x.b > y.b;
}
int main() {

	cin.sync_with_stdio(false);

	int n, t;
	cin >> n >> t;
	for (int i = 0; i < n; i++)
		cin >> tim[i].a >> tim[i].b;
	sort(tim, tim + n , compare);

	int count = 0, i = 0, end = 1;
	bool flag = false;
	while (i < n && tim[i].a <= end) {
		count++;
		int maxn = -1;
		while (i < n && tim[i].a <= end) {
			maxn = (maxn > tim[i].b ? maxn : tim[i].b);		//取最大区间
			i++;
		}
		i--;
		end = maxn;
		if (end >= t) {		//覆盖成功及时停止
			flag = true;
			break;
		}
		end++; i++;
	}
	if (flag) printf("%d\n",count);
	else printf("-1\n");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值