51Nod 1133 不重叠的线段 | 典型贪心

Input示例
3
1 5
2 3
3 6
Output示例
2

题意:给出n条一维线段,求不重合的最多线段数。
解析:这个是典型的贪心算法的区间问题。
贪心策略:每次取尽可能短的区间,而且保证相互之间不重合。那么我们将区间的右边界进行升序排序(左边界要从右往左考虑),然后开循环扫描,维护一个右边界,进行判断。以下是我的代码
 
#include "bits/stdc++.h"
using namespace std;
#define rep(i, s, n) for(int i=s;i<n;i++)
const int N=10010;
struct se{
    int s,e;
}arr[N];
bool cmp(struct se &a,struct se & b){
    return a.e<b.e;
}
int main()
{
    int n;
    while(~scanf("%d",&n)){
        rep(i,0,n)
            scanf("%d%d",&arr[i].s,&arr[i].e);
        sort(arr,arr+n,cmp);
        int cnt=0;
        if(n>0)
        {
            cnt=1;
            int tmp=arr[0].e;
            rep(i,0,n){
                if(arr[i].s>=tmp){
                    cnt++;
                    tmp=arr[i].e;
                }
            }
        }
        printf("%d
",cnt);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/kimsimple/p/7633718.html