标签:family com Stub images override 分享 info lse name
一问题描述
二问题分析
三代码实现
package loading;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
public class bin
{
public static void main(String[] args) throws IOException
{
int []w= {0,30,10,60,40,50,20};
int c=150;
element []ele=new element[w.length-1] ;
for(int i=1; i<w.length; i++)
{
ele[i-1]=new element(w[i],i);
}
greedyLoading myGreedyLoading=new greedyLoading(ele, c);
}
}
class element //集装箱类
{
int w; //重量
int i; //编号
int x=0; //是否上船
public element(int w,int i)
{
this.w=w;
this.i=i;
}
}
class greedyLoading
{
element []ele;
int c; //船的容量
int opt=0; //最优装载
int rc; //剩余载重量
public greedyLoading(element []ele,int c) throws IOException
{
this.ele=ele;
this.c=c;
this.rc=c;
GreedyLoading();
display();
}
public void GreedyLoading()
{
Arrays.sort(ele, new Comparator<element>(){
//传入的时候由用户自己选
@Override
public int compare(element o1, element o2) {
// TODO Auto-generated method stub
int finsh1 = o1.w;
int finsh2 = o2.w;
if (finsh1>finsh2)
{
return 1;
}
else
{
if (finsh1<finsh2)
{
return -1;
}else
{
return 0;
}
}
}
});
for(int i=0; i<ele.length; i++)
{
if(ele[i].w<=rc)
{
ele[i].x=1; //安排
rc-=ele[i].w;
opt+=ele[i].w;
}
else
{
break;
}
}
}
public void display() throws IOException
{
BufferedWriter fout=new BufferedWriter(new FileWriter("out.txt"));
fout.write("c="+c);
fout.newLine();
fout.write("rc="+rc);
fout.newLine();
fout.write("opt="+opt);
fout.newLine();
for(int i=0; i<ele.length; i++)
{
fout.write("ele["+i+"]:");
fout.newLine();
fout.write("i:\t"+ele[i].i);
fout.newLine();
fout.write("s:\t"+ele[i].w);
fout.newLine();
fout.write("x:\t"+ele[i].x);
fout.newLine();
fout.write("+++++++++++++++++++");
fout.newLine();
}
fout.flush();
}
}
enter code here
四运行结果
五总结收获
1.熟练贪心算法
六不足
1.手速太慢
标签:family com Stub images override 分享 info lse name
原文地址:https://www.cnblogs.com/Howbin/p/9919310.html