http://acm.hdu.edu.cn/showproblem.php?pid=2037
贪心算法之典型的时间序列问题。
算法分析:
不妨用Begin[i]和End[i]表示事件i的开始时刻和结束时刻。则原题的要求就是找一个最长的序列a1<a2<…<an,满足:
Begin[a1]<End[a1]<=…<= Begin[an]<End[an]
可以证明,如果在可能的事件a1<a2<…<an中选取在时间上不重叠的最长序列,那么一定存在一个包含a1(结束最早)的最长序列。
先按结束时间进行排序,然后寻找合适的事件就可以了。
#include <iostream>
#include <algorithm>
using namespace std;
#define N 105
struct program_node{
int s,f;
};
program_node program[N];
bool cmp(program_node a,program_node b){
return a.f<b.f;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("2037in.txt","r",stdin);
#endif
int n,i,k,time_e;
while (scanf("%d",&n)!=EOF&&n){
for (i=0;i<n;i++)
scanf("%d%d",&program[i].s,&program[i].f);
sort(program,program+n,cmp);
k=0;
time_e=0;
for (i=0;i<n;i++)
if (time_e<=program[i].s){
time_e=program[i].f;
k++;
}
printf("%d\n",k);
}
return 0;
}