梱包の問題、貪欲なアルゴリズムは、おおよその最適なソリューションを求めています
コードコピーは次のとおりです。
java.util.arraysをインポートします。
java.util.comparatorをインポートします。
//梱包の問題、貪欲なアルゴリズム
パブリッククラスエンチェイゼ{
public void test1(){
integer [] boxes = {34,6,40,2,23,12,12};
int boxcaptation = 40; //ボックス容量
//逆順
arrays.sort(boxs、new Comparator <integer>(){
@オーバーライド
public int Compare(整数O1、整数O2){
O2-O1を返します。
}
});
int unenchase = boxs.length; // boxedの数
int minindex = boxs.length-1; //最小のボックスが指します
while(unenchase> 0){
for(int i = 0; i <boxs.length; i ++){
//位置ボックスの重量はスキップゼロです
if(boxs [i] == 0){
続く;
}
Unenchase--;
while((boxcaptation-boxs [i])> = boxs [minindex]){
int k = i+1;
for(; k> i; k ++){
//位置ボックスの重量はスキップゼロです
if(boxs [k] == 0){
続く;
}
//ボックスを追加して、元の位置をクリアします
ボックス[i]+= boxs [k];
int temp = boxs [k];
ボックス[k] = 0;
Unenchase--;
if(boxs [i]> boxcaptation){
//最大容量を超えることができ、ステータスが復元されます
Unenchase ++;
ボックス[k] =温度;
boxes [i] - = boxs [k];
続く;
}
//最小ボックスの更新
if(k == minindex){
for(int y = minindex; y> 0; y - ){
if(boxs [y]!= 0){
minindex = y;
}
}
}
壊す;
}
}
}
}
//ボックスの数をカウントします
int boxcount = 0;
System.out.println( "ボクシング結果:");
for(int i = 0; i <boxs.length; i ++){
System.out.print(boxs [i]+"/t");
if(boxs [i] == 0){
続く;
}
BoxCount ++;
}
System.out.println( "/nnumber of Boxes:"+boxcount);
}
public static void main(string [] args){
new Enchase()。test1();
}
}
上記はこの記事のすべてです。あなたがそれを気に入ってくれることを願っています。