例6.6 整数区间

请编程完成以下任务:   
1.从文件中读取闭区间的个数及它们的描述;
2.找到一个含元素个数最少的集合,使得对于每一个区间,都至少有一个整数属于该集合,输出该集合的元素个数。
【输入】
首行包括区间的数目n,1<=n<=10000,接下来的n行,每行包括两个整数a,b,被一空格隔开,0<=a<=b<=10000,它们是某一个区间的开始值和结束值。
【输出】
第一行集合元素的个数,对于每一个区间都至少有一个整数属于该区间,且集合所包含元素数目最少。
【样例输入】
4
3 6
2 4
0 2
4 7
【样例输出】
2

#include <cstdio>
#include <algorithm>
using namespace std;
typedef struct {
	int l, r;
}Section;
bool cmp(Section x, Section y) {
	if (x.r < y.r) return true;
	if (x.r > y.r) return false;
	else
		if (x.l < y.l) return true;
		else return false;
}
int main() {
	int n, minsec = 1;
	Section sec[10005];
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d %d", &sec[i].l, &sec[i].r);
	}
	sort(sec, sec + n, cmp);
	int t = sec[0].r;
	for (int i = 1; i < n; i++) {
		if (sec[i].l > t) {
			t = sec[i].r;
			minsec++;
		}
	}
	printf("%d\n", minsec);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值