题目描述
Being a fan of all cold-weather sports (especially those involving cows),Farmer John wants to record as much of the upcoming winter Moolympics as possible.
The television schedule for the Moolympics consists of N different programs(1 <= N <= 150), each with a designated starting time and ending time. FJ has a dual-tuner recorder that can record two programs simultaneously.
Please help him determine the maximum number of programs he can record in total.
农民约翰热衷于所有寒冷天气的运动(尤其是涉及到牛的运动), 农民约翰想记录尽可能多的moolympics为即将到来的冬季 可能的。 为moolympics电视时间表由N个不同的程序 (1 < = n=150),每个具有指定的开始时间和结束时间。FJ 有一个双调谐器录音机,可以同时录制两个节目。 请帮助他确定他能录制的节目的最大数量。
输入输出格式
输入格式:
* Line 1: The integer N.
* Lines 2..1+N: Each line contains the start and end time of a single program (integers in the range 0..1,000,000,000).
第1行:整数n。 第2行.. 1 + n:每行包含单个的开始和结束时间 程序(范围为0…1000000000的整数)。
输出格式:
* Line 1: The maximum number of programs FJ can record.
仅一行,节目FJ可以记录的最大数量。
输入输出样例
说明
INPUT DETAILS:
The Moolympics broadcast consists of 6 programs. The first runs from time 0 to time 3, and so on.
OUTPUT DETAILS:
FJ can record at most 4 programs. For example, he can record programs 1 and 3 back-to-back on the first tuner, and programs 2 and 4 on the second tuner.
Source: USACO 2014 January Contest, Silver
正解:
贪心(证明略)。
把节目看成数轴上的每条线段,那么就相当于有两次机会选最多的线段条数
并且他们没有公共点
我们维护两台摄像机能够到达的最远的地方,
t1 --较远的
t2--较近的
对线段进行排序(右端点递增,然后左端点递减)后
如果
更新t1,
----------------------------------------------------------------------
如果
更新t1和t2
(详见代码)
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cmath> 5 #define ll long long 6 #include<cstring> 7 #include<string> 8 #define DB double 9 using namespace std; 10 int n,t1,t2,ans; 11 struct node{ 12 int s,t; 13 friend bool operator<(node x,node y) 14 { 15 if(x.t!=y.t) return x.t<y.t; 16 else return x.s>y.s; 17 } 18 }a[200]; 19 int main() 20 { 21 scanf("%d",&n); 22 for(int i=1;i<=n;++i) scanf("%d%d",&a[i].s,&a[i].t); 23 sort(a+1,a+n+1); 24 t1=t2=-1; 25 for(int i=1;i<=n;++i) 26 { 27 if(a[i].s>=t1) t1=a[i].t,ans++; 28 else if(a[i].s>=t2) t2=a[i].t,ans++,swap(t1,t2); 29 } 30 printf("%d",ans); 31 return 0; 32 }
可见天地不可一日无和气,人心不可一日无喜神。