Packing problem, greedy algorithm to find the approximate optimal solution
Copy Code code as follows:
Import Java.util.Arrays;
Import Java.util.Comparator;
Packing problem, greedy algorithm
public class Enchase {
public void Test1 () {
Integer[] boxs={34,6,40,2,23,12,12};
int boxcaptation=40;//Box capacity
Reverse
Arrays.sort (Boxs, New comparator<integer> () {
@Override
public int Compare (integer o1, integer o2) {
return o2-o1;
}
});
int unenchase=boxs.length;//unboxed Number
int minindex=boxs.length-1;//the smallest box pointing
while (unenchase>0) {
for (int i=0;i<boxs.length;i++) {
Position box weight of 0 skipped
if (boxs[i]==0) {
Continue
}
unenchase--;
while ((Boxcaptation-boxs[i]) >=boxs[minindex]) {
int k=i+1;
for (; k>i;k++) {
Position box weight of 0 skipped
if (boxs[k]==0) {
Continue
}
Add the box to the original position clear zero
BOXS[I]+=BOXS[K];
int temp=boxs[k];
boxs[k]=0;
unenchase--;
if (boxs[i]>boxcaptation) {
More than maximum capacity, state recovery
unenchase++;
Boxs[k]=temp;
BOXS[I]-=BOXS[K];
Continue
}
Minimum box update
if (K==minindex) {
for (int y=minindex;y>0;y--) {
if (boxs[y]!=0) {
Minindex=y;
}
}
}
Break
}
}
}
}
Statistics Box Number
int boxcount=0;
SYSTEM.OUT.PRINTLN ("Packing result:");
for (int i=0;i<boxs.length;i++) {
System.out.print (boxs[i]+ "T");
if (boxs[i]==0) {
Continue
}
boxcount++;
}
System.out.println ("\ n Box Number:" +boxcount);
}
public static void Main (string[] args) {
New Enchase (). Test1 ();
}
}
The above is the entire content of this article, I hope you can enjoy.