•public static float knapsack(float c,float [] w, float [] v,float [] x)
• {
• int n=v.length;
• Element [] d = new Element [n];
• for (int i = 0; i < n; i++) d[i] = new Element(w[i],v[i],i);
• MergeSort.mergeSort(d); / /按单位价值由高道低排序
• int i;
• float opt=0;
• for (i=0;i<n;i++) x[i]=0;
• for (i=0;i<n;i++) {
• if (d[i].w>c) break;
• x[d[i].i]=1; / /标记i的物品已被装入背包
• opt+=d[i].v;
• c-=d[i].w;
• }
• if (i<n){
• x[d[i].i]=c/d[i].w;
• opt+=x[d[i].i]*d[i].v;
• } / /把背包装满
• return opt;
• }
本文介绍了一种解决0-1背包问题的算法实现,通过计算每个物品的价值密度并进行排序来决定装入背包的物品顺序,确保在背包容量限制下获得最大价值。
284

被折叠的 条评论
为什么被折叠?



