贪心复习

前言

复习一下贪心算法,主要涉及俩个经典题目,这里重现一下,活动选择和部分背包问题,主要分三部分,贪心的基本概念,活动选择,部分背包问题。

贪心的基本概念

所谓贪心选择性质是指所求问题的整体最优解可以通过一系列局部最优的选择,即贪心选择来达到。这是贪心算法可行的第一个基本要素,也是贪心算法与动态规划算法的主要区别。在动态规划算法中,每步所做的选择往往依赖于相关子问题的解。因而只有在解出相关子问题后,才能做出选择。而在贪心算法中,仅在当前状态下做出最好选择,即局部最优选择。然后再去解出做出这个选择后产生的相应的子问题。贪心算法所做的贪心选择可以依赖于以往所做过的选择,但决不依赖于将来所做的选择,也不依赖于子问题的解。正是由于这种差别,动态规划算法通常以自底向上的方式解各个问题,而贪心算法则通常以自顶向下的方式进行,以迭代的方式做出相继的贪心选择,没做一次贪心选择就将所求问题简化为规模更小的子问题。
对于一个具体问题,要确定它是否具有贪心选择性质,必须证明每一步所做的贪心选择最终导致问题的整体最优解。

活动选择


#include<iostream>
#include<algorithm>
using namespace std;

//define the structor
struct DataType
{
 int startTime;
 int endTime;
};


bool compare(DataType a,DataType b)
{
	return a.endTime<b.endTime;

}

void GreedySelect(DataType* time ,int n)
{
	sort(time,time+n,compare);//先排序
    int tmp=0;
	cout<<time[0].startTime<<":"<<time[0].endTime<<endl;
	for(int i=1;i<n;++i)
	{   
        
		if(time[i].startTime>time[tmp].startTime)
		{
		 tmp=i;
		 cout<<time[i].startTime<<":"<<time[i].endTime<<endl;
		}
	}

}

const int N=4;
int main()
{
   DataType time[N]={{3,5},{1,2},{4,9},{5,6}};
   GreedySelect(time,N);
   return 0;
}


部分背包问题

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct Goods
{
  int value;//价值
  int weight;//物品重量
  double ValuePweight;//单位重量的价值
};

struct SavedGoods
{
queue<Goods>* qG;
int residue;

};

bool compare(Goods a,Goods b)
{
	return a.ValuePweight<b.ValuePweight;

}

const int N=6;

SavedGoods* SelectGoods(Goods* pG,int N,int MaxW)
{
  queue<Goods>* qG=new queue<Goods>();
  int tmp;
  int sum=0;
  for(int i=0;i<N;++i)
  {
	  sum+=pG[i].weight;
   if(sum<= MaxW)
   {
	   qG->push(pG[i]);
	   continue;
   }
   else
   {
	   sum-=pG[i].weight;
    tmp= MaxW-sum;
    qG->push(pG[i]);
    break; 
   }
  
  }
  SavedGoods* pSG=new  SavedGoods();
  pSG->qG=qG;
  pSG->residue=tmp;
  return pSG;
}
int main()
{
	int V[N]={5,2,8,6,9,7};
	int W[N]={6,3,1,3,5,3};
    Goods goodSet[N];
	for(int i=0;i<N;++i)
	{
		goodSet[i].value=V[i];
		goodSet[i].weight=W[i];
		goodSet[i].ValuePweight=V[i]*1.0/W[i]*1.0;
	}

   sort(goodSet,goodSet+6,compare);
   SavedGoods* pSG=SelectGoods(goodSet, N,15);
   int valu;
   int weigh;
  while(!pSG->qG->empty())
  {
	 valu= pSG->qG->front().value;
	 weigh= pSG->qG->front().weight;
	  cout<<valu<<":"<< weigh<<endl;
     pSG->qG->pop();
  }
  cout<<pSG->residue;
   return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值