贪心算法-活动选择

问题描述
问题来自算法导论16.1。

几个相互竞争的活动进行调度,他们要求以独占的方式使用某一公共资源。调度的目标是找出一个最大的相互兼容活动集合。

思想:总是选择剩余活动中具有最早结束时间的活动。

/*****************************************************************************
Copyright: 2012, USTC
File name: main.cpp
Description:Arrange activities by greedy method.
Author:Silang Quan
Version: 1.0
Date: 2012.12.3
*****************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
//Iteration Method assume a[1] is the first activity meet the need.
int GreedySelect(int *s,int *f,int length,int *a)
{
	int i,j=2;
	a[1]=1;
	i=1;
	for(int m=2;m<=length;m++)
	{
		if(s[m]>=f[i])
		{
			a[j++]=m;
			i=m;
		}
	}
	return j;
}
//Recursion method
void GreedySelect2(int *s,int *f,int i,int j,vector<int>& result)// const int started[], const int finished[],vector<int>& result, int i,int j)
{
    if( i >= j ) return;
    int l;
    for( l = i+1; l < j; ++l )
    {
        if( s[l] >= f[i] )
        {
            result.push_back(l);
            break;
        }
    }
    GreedySelect2(s,f,l,j,result);
}
int main()
{
	int s[12]={0,1,3,0,5,3,5,6,8,8,2,12};
	int f[12]={0,4,5,6,7,8,9,10,11,12,13,14};
	//test1
	/*
	int a[13];
	int i=GreedySelect(s,f,11,a);

	for(int j=1;j<i;j++)
	{
		cout<<a[j]<<" ";
	}
	cout<<endl;
	*/
	//test2
    vector<int> result;
    GreedySelect2(s,f,0,12,result);
    for(vector<int>::iterator iter=result.begin();iter!=result.end();++iter)
    {
        cout<<*iter<<" ";
    }
    cout<<endl;
}



参考:

算法导论,第二版,机械工业出版社

算法导论-贪心算法-http://blog.csdn.net/liuzhanchen1987/article/details/7854826

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值