(算法练习)——看电视

要求:
http://codeup.cn/problem.php?cid=100000584&pid=0
说明:
这一题的实质还是区间贪心,拿书上的代码直接就过了
代码:

#include <stdio.h>
#include <algorithm>
using namespace std;

const int maxn = 110;
struct Inteval{
	int x,y;
}I[maxn];

bool cmp(Inteval a,Inteval b){
	if(a.x != b.x) return a.x > b.x;
	else return a.y < b.y;
}

int main(){
	int n;
	while(scanf("%d",&n),n != 0){
		for(int i = 0;i <n;i++){
			scanf("%d %d",&I[i].x,&I[i].y);
		}
		//排序,从大的区间向小的区间排
		sort(I,I+n,cmp);
		int ans = 1,lastX = I[0].x;
		for(int i = 1;i <n;i++){
			if(I[i].y <= lastX){//如果该区间右端点在lastX左边
				lastX = I[i].x;//以I[i]作为新选中的区间
				ans++;//不相交区间个数加1
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}
发布了105 篇原创文章 · 获赞 3 · 访问量 1961

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104010261