贪心算法的基本思路是从问题的某一个初始解出发一步一步地进行,根据某个优化测度,每一步都要确保能获得局部最优解。每一步只考虑一个数据,他的选取应该满足局部优化的条件。若下一个数据和部分最优解连在一起不再是可行解时,就不把该数据添加到部分解中,直到把所有数据枚举完,或者不能再添加算法停止
值得注意的是贪心算法需要证明后才能真正运用到题目的算法中。贪心算法的证明围绕着:整个问题的最优解一定由在贪心策略中存在的子问题的最优解得来的。
下面是一个比较简单的贪心算法的案例
Problem Description
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.
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
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 typedef struct Goods 5 { 6 double weight; //重量 7 double price; //价格 8 double cost; //性价比 9 10 } Goods; 11 Goods g[1002]; 12 13 int cmp( const void *a,const void *b); 14 15 int main() 16 { 17 int n; 18 double m,ret; 19 int i; 20 int index = 0; //货物下标 21 22 while( scanf("%lf%d",&m,&n)!=EOF) 23 { 24 if( m==-1 && n==-1) break; 25 26 for( i=0 ; i<n; i++) 27 { 28 scanf("%lf%lf",&g[i].weight,&g[i].price); 29 g[i].cost = g[i].weight/g[i].price; 30 } 31 32 qsort( g,n,sizeof( g[0]),cmp); //对性价比进行降序排序 33 while( m>0 && index<n) 34 { 35 if( m > g[index].price) 36 { 37 //钱够买下全部物品 38 ret += g[index].weight; 39 m -= g[index].price; 40 } 41 else 42 { 43 //只能买下部分物品 44 ret += g[index].weight * m / g[index].price; 45 m = 0; 46 } 47 index ++; 48 } 49 printf("%.3lf\n",ret); 50 51 } 52 return 0; 53 } 54 55 int cmp( const void *a,const void *b) 56 { 57 Goods *c = (Goods *)a; 58 Goods *d = (Goods *)b; 59 return (d->cost > c->cost) ? 1:-1; 60 }