题目描述:
设有n个活动的集合E={1,2,…,n},其中每个活动都要求使用同一资源,如演讲会场等,而在同一时间内只有一个活动能使用这一资源。
每个活动i都有一个要求使用该资源的起始时间si和一个结束时间fi,且si<fi。如果选择了活动i,则它在半开时间区间[si ,fi )内占用资源。若区间[si ,fi )与区间[sj,fj )不相交,则称活动i与活动j是相容的。当 si ≥ fj 或 sj ≥ fi 时,活动i与活动j相容。
活动安排问题就是在所给的活动集合中选出最大的相容活动子集合。
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
/**活动安排问题*/
struct action{
int s;
int f;
int index;
};
bool cmp(const action &a,const action &b){
if(a.f<=b.f) return true;
return false;
}
void GreedySelector(int n, action a[], bool b[])
{
b[1] = true;
int preEnd = 1;
for(int i=2; i<=n; i++)
if (a[i].s>=a[preEnd].f)
{
b[i] = true;
preEnd = i;
}
}
int main()
{
int n;
while(cin>>n && n)
{
action a[1000];
bool b[1000];
memset(b,false,sizeof(b));
for(int i=1; i<=n; i++)
{
cin>>a[i].s>>a[i].f;
a[i].index = i;
}
sort(a, a+n+1, cmp);
GreedySelector(n, a, b);
for(int i=1; i<=n;i++)
if(b[i]) cout<<a[i].index<<" ";
cout<<endl;
}
return 0;
}