贪心算法--活动安排

题目描述:

设有n个活动的集合E{12n},其中每个活动都要求使用同一资源,如演讲会场等,而在同一时间内只有一个活动能使用这一资源

每个活动i都有一个要求使用该资源的起始时间si和一个结束时间fi,且sifi。如果选择了活动i,则它在半开时间区间[si fi )内占用资源。若区间[si fi )与区间[sjfj )不相交,则称活动i与活动j相容的。当 si fjsj 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;
}
发布了81 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41499217/article/details/102672042