首页 > 代码库 > hdu2037 今年暑假不AC (贪心)

hdu2037 今年暑假不AC (贪心)

Problem Description
http://acm.hdu.edu.cn/showproblem.php?pid=2037
作为球迷,一定想看尽量多的完整的比赛,当然,作为新时代的好青年,你一定还会看一些其它的节目,比如新闻联播(永远不要忘记关心国家大事)、非常6+7、超级女生,以及王小丫的《开心辞典》等等,假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)
 
Input
输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n<=100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据Ti_s,Ti_e (1<=i<=n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0表示输入结束,不做处理。
 
Output
对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。
 
Sample Input
12 1 3 3 4 0 7 3 8 15 19 15 20 10 15 8 18 6 12 5 10 4 14 2 9 0
 
Sample Output
5
题目分析:
简单的贪心策略,见代码。

AC代码:
/**
 *贪心算法
 */
#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<cstdlib>
#include<cctype>
#include<cstring>
#include<cmath>
using namespace std;
struct node{
    int b,e;//时间
};
node a[255];
int cmp(node a,node b){
    if(a.b<b.b) return 1;
    else if(a.b==b.b&&a.e<b.e) return 1;//开始和结束的时间相同的话,结束的时间排在前面
    return 0;
}
int main()
{
    int n,b,e;
    while(cin>>n&&n){
        int k=0;
        for(int i=0;i<n;i++){
            cin>>b>>e;
            a[i].b=b;
            a[i].e=e;
        }
        sort(a,a+n,cmp);
        int sum=1;
        node p=a[0];
        for(int i=1;i<n;i++){//遇到结束点就加1,遇到起点减1
            if(a[i].b>=p.e){
                sum++;
                p=a[i];
            }
            else if(a[i].e<=p.e){
                p=a[i];
            }
        }
        cout<<sum<<endl;
    }
    return 0;
}


 

hdu2037 今年暑假不AC (贪心)