题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2037
活动安排问题,可用贪心。
1、把活动按结束时间递增排序。
2、直观上,选择相对活动为未安排活动留下尽可能多的时间。
#include <cstdio> #include <algorithm> #include <string.h> using namespace std; struct action { int s;///开始时间 int f;///结束时间 int index;///活动标号 }; action a[105]; bool b[105]; bool cmp(const action &a,const action &b) { if(a.f<=b.f) return true; else return false; } void GreedySelector(int n,action a[],bool b[]) { b[0]=true;///第一个活动必须选 ///记录最近一次加入到集合b中的活动 int preEnd=0; for(int i=1; i<n; i++) { if(a[i].s>=a[preEnd].f) { b[i]=true; preEnd=i; } } } int main() { int n; while(scanf("%d",&n),n) { memset(b,false,sizeof(b)); for(int i=0; i<n; i++) { scanf("%d%d",&a[i].s,&a[i].f); ///a[i].index=i; } sort(a,a+n,cmp); GreedySelector(n,a,b); int Max=0; for(int i=0; i<n; i++) { if(b[i]) Max++; } printf("%d ",Max); /*for(int i=0;i<n;i++) { if(b[i]) printf("%d ",a[i].index); } printf(" ");*/ } }