亲宝软件园·资讯

展开

c语言来实现贪心算法之装箱问题 c语言来实现贪心算法之装箱问题

人气:1
想了解c语言来实现贪心算法之装箱问题的相关内容吗,在本文为您仔细讲解c语言来实现贪心算法之装箱问题的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c语言,贪心算法,装箱问题,下面大家一起来学习吧。

装箱问题,贪心算法求近似最优解

复制代码 代码如下:

import java.util.Arrays;
import java.util.Comparator;
//装箱问题,贪心算法
public class Enchase {
    public void test1() {
        Integer[] boxs={34,6,40,2,23,12,12};
        int boxCaptation=40;//箱子容量
        //倒序
        Arrays.sort(boxs, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        int unEnchase=boxs.length;//未装箱数
        int minIndex=boxs.length-1;//最小的箱子指向
        while (unEnchase>0) {
            for(int i=0;i<boxs.length;i++){
                //位置箱子重量为零跳过
                if(boxs[i]==0){
                    continue;
                }
                unEnchase--;
                while((boxCaptation-boxs[i])>=boxs[minIndex]){
                    int k=i+1;
                    for(;k>i;k++){
                        //位置箱子重量为零跳过
                        if(boxs[k]==0){
                            continue;
                        }
                        //将箱子加上去,原来位置清零
                        boxs[i]+=boxs[k];
                        int temp=boxs[k];
                        boxs[k]=0;
                        unEnchase--;
                        if(boxs[i]>boxCaptation){
                            //超过最大可容纳体积,状态复原
                            unEnchase++;
                            boxs[k]=temp;
                            boxs[i]-=boxs[k];
                            continue;
                        }
                        //最小箱子更新
                        if(k==minIndex){
                            for(int y=minIndex;y>0;y--){
                                if(boxs[y]!=0){
                                    minIndex=y;
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
        //统计箱子数
        int Boxcount=0;
        System.out.println("装箱结果:");
        for(int i=0;i<boxs.length;i++){
            System.out.print(boxs[i]+"\t");
            if(boxs[i]==0){
                continue;
            }
            Boxcount++;
        }
        System.out.println("\n箱子数:"+Boxcount);
    }
    public static void main(String[] args) {
        new Enchase().test1();
    }
}

以上就是本文的全部内容了,希望大家能够喜欢。

加载全部内容

相关教程
猜你喜欢
用户评论