贪心算法:
在求解最优解问题中,我们依据某种贪心的准则寻找每一个小区间的最优解,再通过每一个小区间的最优解找到整个区间的最优解,这种方法就是所谓的贪心算法。
贪心算法不是一个从整个问题出发寻找最优解的方法,而是一种从整体的部分来寻找最优解的方法,在寻找了局部最优解的同时,由该问题的特性选择一种贪心的方式,从而得到你所选贪心方式的最优解。如果一个问题有若干种解法,那么贪心算法则是最优选择。
贪心算法的一般流程:
greddy(A)
{s={}; //初始解集为空
while(not solution(s)) //集合s未构成问题的一个解
{
x=select(A);//在候选集合A中以某种规则进行贪心选择,既找到分问题的最优解
if feasible(S,X)//判断X加入到s中是否符合要求
S=S+{x};
A=A-{x};
}
return S;
}
贪心算法的一种实现:背包问题:
附一道题目:
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.
Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
Sample Input
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
Sample Output
13.333 31.500
大意是老鼠换粮食,而每个仓库的粮食价格又不同,那么最好的方法就是性价比了,也就是变为一个量度来衡量,比如如今我们买菜的价格,这个使用猫粮换豆子,那么用猫粮除以豆子作为性价比,将其进行从大到小排列,然后一点点加,直到猫粮用完,这就是我们可以得到的最大,当然如果换不来一个仓库的全部豆子,我们就以比列进行兑换,这就是贪心算法的基本实现方式,code:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int a,f=1,b,c;
struct X
{
int a;
int b;
double c;
}h[1100];
bool cop(X a,X b)
{
return a.c>b.c;
}
int main()
{double d;
int m,n,f;
while(cin>>m>>n)
{
if(m==-1&&n==-1) break;
for(int i=1;i<=n;++i)
{
cin>>h[i].a>>h[i].b;
h[i].c=(double)h[i].a/h[i].b;
}
sort(h+1,h+n+1,cop);
f=1;d=0;
while(n)
{
if(h[f].b<m) {m-=h[f].b;d+=h[f].a;f++;}
else {d+=1.0*(double)m*(double)h[f].a/(double)h[f].b;break;}
}
printf("%.3f\n",d);
}
return 0;
}
贪心算法在根本上就是一种找最优解的思维方式,在分问题上或者是分级处理找到最优解进而找到总体的最优解。