首页 > 技术文章 > 区间贪心算法

zuimeiyujianni 2018-03-07 18:51 原文

/*
    区间贪心算法:
    区间不相交问题,给出n个开区间(x,y),从中选择尽可能多的开区间,使得这些区间亮亮没有交集 
*/
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 110; 
struct Inteval{
    int x , y;
}I[maxn];
int cmp(Inteval a , Inteval b){
    //先按左端点从大到小排序,左端点相同按右断点从小到大排序 
    if( a.x != b.x ) return a.x > b.x;
    else return a.y < b.y;
}
int main(void){
    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 = I[i].x;
                ans++;
            }
        }
        cout << ans;
    }
}

 

推荐阅读