c語言來實現貪心演算法之裝箱問題_java

來源:互聯網
上載者:User

裝箱問題,貪心演算法求近似最優解

複製代碼 代碼如下:

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

以上就是本文的全部內容了,希望大家能夠喜歡。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.