贪心算法 背包问题.doc

上传人:hw****26 文档编号:3497956 上传时间:2019-05-31 格式:DOC 页数:7 大小:36.50KB
下载 相关 举报
贪心算法 背包问题.doc_第1页
第1页 / 共7页
贪心算法 背包问题.doc_第2页
第2页 / 共7页
贪心算法 背包问题.doc_第3页
第3页 / 共7页
贪心算法 背包问题.doc_第4页
第4页 / 共7页
贪心算法 背包问题.doc_第5页
第5页 / 共7页
点击查看更多>>
资源描述

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();

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 实用文档资料库 > 策划方案

Copyright © 2018-2021 Wenke99.com All rights reserved

工信部备案号浙ICP备20026746号-2  

公安局备案号:浙公网安备33038302330469号

本站为C2C交文档易平台,即用户上传的文档直接卖给下载用户,本站只是网络服务中间平台,所有原创文档下载所得归上传人所有,若您发现上传作品侵犯了您的权利,请立刻联系网站客服并提供证据,平台将在3个工作日内予以改正。