c語言來實現(xiàn)貪心算法之裝箱問題
更新時間:2015年03月13日 14:54:51 投稿:hebedich
這篇文章主要介紹了c語言來實現(xiàn)貪心算法之裝箱問題,需要的朋友可以參考下
裝箱問題,貪心算法求近似最優(yōu)解
復(fù)制代碼 代碼如下:
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;//未裝箱數(shù)
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){
//超過最大可容納體積,狀態(tài)復(fù)原
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;
}
}
}
}
//統(tǒng)計箱子數(shù)
int Boxcount=0;
System.out.println("裝箱結(jié)果:");
for(int i=0;i<boxs.length;i++){
System.out.print(boxs[i]+"\t");
if(boxs[i]==0){
continue;
}
Boxcount++;
}
System.out.println("\n箱子數(shù):"+Boxcount);
}
public static void main(String[] args) {
new Enchase().test1();
}
}
以上就是本文的全部內(nèi)容了,希望大家能夠喜歡。
相關(guān)文章
SpringBoot2 task scheduler 定時任務(wù)調(diào)度器四種方式
這篇文章主要介紹了SpringBoot2 task scheduler 定時任務(wù)調(diào)度器四種方式,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-03-03Spring Boot JPA中java 8 的應(yīng)用實例
這篇文章主要介紹了Spring Boot JPA中java 8 的應(yīng)用實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2020-02-02macOS上使用gperftools定位Java內(nèi)存泄漏問題及解決方案
這篇文章主要介紹了macOS上使用gperftools定位Java內(nèi)存泄漏問題,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07詳解Spring ApplicationContext加載過程
這篇文章主要介紹了Spring ApplicationContext加載過程的相關(guān)資料,幫助大家更好的理解和學(xué)習使用spring框架,感興趣的朋友可以了解下2021-03-03