区间贪心

来源:互联网 发布:云数据分析 编辑:程序博客网 时间:2024/06/05 18:25

区间不想交问题:给出N个开区间(x,y),从中选择尽可能多的开区间,使得这些开区间,两两没有交集

输入:

4
1 3
2 4
3 5
6 7

输出:
3

#include<stdio.h>#include<algorithm>using namespace std;struct inteval{int x,y;//开区间左右端点 }I[110];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;//ans记录不想交区间个数,lastx记录上一个被选中区间的左端点 int lastx=I[0].x;for(int i=1;i<n;i++){if(I[i].y<=lastx)//如果该区间右端点在lastx左边 {lastx=I[i].x;//以I[x]作为新选中的区间 ans++; //不相交区间个数 }}printf("%d",ans);}return 0;}


原创粉丝点击