码迷,mamicode.com
首页 > 其他好文 > 详细

nyoj891(区间上的贪心)

时间:2017-05-27 21:50:00      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:区间贪心   line   使用   pop   贪心   end   mil   acm   content   

题目意思:

给一些闭区间,求最少须要多少点,使得每一个区间至少一个点。

http://acm.nyist.net/JudgeOnline/problem.php?pid=891

例子输入
4
1 5
2 4
1 4
2 3
3
1 2
3 4
5 6
1
2 2
例子输出
1
3
1
题目分体:

区间贪心。我觉得区间上的贪心算法,最基本的还是排序的方式。仅仅要排序的方式合理。就能非常好的使用贪心,贪心的本质尽管是选择当前最优的解,作为全军最优解的一部分。假设排序不当回造成好的条件选择。本题仅仅给出的排序的方式。相信大家都会使用贪心的。


AC代码:

 
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
    int r,l;
}a[101];
int cmp(node a1,node b1){//按右端点从大到小,左端点从大到小定义排序方式。


    if(a1.r<b1.r) return 1;
    else if(a1.r==b1.r&&a1.l>b1.l) return 1;
    return 0;
}
int main()
{
    int n;
    while(cin>>n){
        int x,y;
        for(int i=0;i<n;i++){
            cin>>x>>y;
            a[i].l=x<y?x:y;
            a[i].r=x>y?x:y;
        }
        sort(a,a+n,cmp);
        int k=1;
        node p=a[0];
        for(int i=1;i<n;i++){
            if(p.r<a[i].l){//当前区间在下一区间左边
                p=a[i]; k++;
            }
        }
        cout<<k<<endl;
    }
    return 0;
}
       

nyoj891(区间上的贪心)

标签:区间贪心   line   使用   pop   贪心   end   mil   acm   content   

原文地址:http://www.cnblogs.com/zhchoutai/p/6914444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!