1、贪心算法 背包问题.txt 精神失常的疯子不可怕,可怕的是精神正常的疯子!#include#includeusing namespace std;struct good/表示物品的结构体double p;/价值double w;/重量double r;/价值与重量的比a2000;double s,value,m;int i,n;bool bigger(good a,good b)return a.rb.r;int main()scanf(“%d“,/物品个数for (i=0;i0,1#define MAXSIZE 100 /假设物体总数#define M 20 /背包的载荷能力/算法核心,贪心
2、算法void GREEDY(float w, float x, int sortResult, int n)float cu = M;int i = 0;int temp = 0;for (i = 0; i cu)break;xtemp = 1;/若合适则取出cu -= wtemp;/将容量相应的改变if (i = n)/使背包充满xtemp = cu / wtemp;return;void sort(float tempArray, int sortResult, int n)int i = 0, j = 0;int index = 0, k = 0;for (i = 0; i n; i+)
3、/对映射数组赋初值 0sortResulti = 0;for (i = 0; i n; i+)float temp = tempArrayi;index = i;/找到最大的效益并保存此时的下标for (j = 0; j n; j+)if (temp tempArrayj) index = j;/对 wi作标记排序if (sortResultindex = 0)sortResultindex = +k;/修改效益最低的 sortResulti标记for (i = 0; i n; i+)if (sortResulti = 0)sortResulti = +k;return;/得到本算法的所有输入
4、信息void getData(float p, float w, int *n)int i = 0;printf(“please input the total count of object: “);scanf(“%d“, n);printf(“Please input array of p :n“);for (i = 0; i (*n); i+)scanf(“%f“, printf(“Now please input array of w :n“);for (i = 0; i (*n); i+)scanf(“%f“, return;void output(float x, int n)in
5、t i;printf(“nnafter arithmetic data: advise methodn“);for (i = 0; i n; i+)printf(“x%dt“, i);printf(“n“);for (i = 0; i n; i+)printf(“%2.3ft“, xi);return;void main()float pMAXSIZE, wMAXSIZE, xMAXSIZE;int i = 0, n = 0;int sortResultMAXSIZE;getData(p, w, for (i = 0; i n; i+)xi = pi / wi;sort(x, sortResult, n);GREEDY(w, x, sortResult, n);output(x, n);getch();