HDU 2037 今年暑假不AC(贪心)

来源:互联网 发布:网络支付跨行代付 编辑:程序博客网 时间:2024/06/03 22:56

问题描述:
假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)

样例输入:
输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n<=100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据Ti_s,Ti_e (1<=i<=n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0表示输入结束,不做处理。

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

样例输出:
对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。

5

思路:活动安排问题,简单的贪心,将所有节目按照结束时间非减进行排列,然后将可以加入的节目存入栈中,每次比较下一个节目的开始时间与前一个加入的节目的结束时间是否冲突即可。

AC代码:

#include <cstdio>#include <algorithm>#include <stack>using namespace std;typedef struct Node{    int s, f;}Node;int cmp(Node n1, Node n2){    return n1.f <= n2.f;}int main(){    int n;    while(~scanf("%d", &n) && n != 0)    {        int x, y;        Node node[n];        stack<Node> temp;        for(int i = 0; i < n; i++)        {            scanf("%d %d", &x, &y);            node[i].s = x;            node[i].f = y;        }        sort(node, node + n, cmp);        int cnt = 1;        temp.push(node[0]);        for(int i = 1; i < n; i++)        {            if(node[i].s >= temp.top().f)            {                cnt++;                temp.push(node[i]);            }        }        printf("%d\n", cnt);    }    return 0;}
0 0
原创粉丝点击