今年暑假不AC(简单贪心)

今年暑假不AC

由于题目要求能观看完整节目的最大值,考虑到关于最值的相关算法以及本题的具体要求,因此采用贪心的做法(其他做法未尝试,DP应该也能做出来)。

首先需要对时间段进行排序。

排序的要点是对时间段的右端点排序,这样在选取节目时只需要考虑左端点的选择,由于已经按照右端点排好序,那么下面只需要从第一个节目(时间长度最小的)开始进行遍历就可以了。

不过需要注意的是在进行遍历的时候,假设第 i + 1 个节目可以排在第 i 个节目后面,那么直接排就行了,因为右端点已经是固定好的了,而且在排好后,需要将当前点移到这个第 i + 1 个节目上,然后再进行下面节目的遍历,直到结束。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 struct Node{
 7     int s, e;
 8 }node[105];
 9 
10 bool cmp(Node a, Node b){
11     return a.e <= b.e;
12 }
13 int main(){
14     int n;
15     while(cin >> n){
16         if(n == 0)
17             break;
18         for(int i = 1; i <= n; i ++)
19             cin >> node[i].s >> node[i].e;
20         sort(node + 1, node + n + 1, cmp);
21         int cnt = 0;
22         //按照右端排序后就只需要考虑左端,
23         for(int i = 1, j = 2; j <= n; j ++){
24             if(node[j].s >= node[i].e){
25                 cnt ++;
26                 i = j;
27             }
28         }
29         cout << cnt + 1 << endl;
30     }
31 
32     return 0;
33 }

 

原文地址:https://www.cnblogs.com/pureayu/p/13905686.html