标签:++ gradient 贪心 ret over params family repeat col
一 问题描述
二 问题分析
**三 代码实现
package knapsnap;
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,10,20,30};
int []v= {0,60,100,120};
int c=50;
element []ele=new element[w.length-1] ;
for(int i=1; i<w.length; i++)
{
ele[i-1]=new element(w[i],v[i],i);
}
greedyLoading myGreedyLoading=new greedyLoading(ele, c);
}
}
class element //集装箱类
{
float w; //重量
float v; //价值
int i; //编号
float x=0; //是否上船
public element(int w,int v, int i)
{
this.w=w;
this.v=v;
this.i=i;
}
}
class greedyLoading
{
element []ele;
float c; //船的容量
float rc; //剩余载重量
float optv=0; //最优价值
float optw=0; //最优载重
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
float finsh1 = o1.v/o1.w;
float finsh2 = o2.v/o2.w;
if (finsh1>finsh2)
{
return -1;
}
else
{
if (finsh1<finsh2)
{
return 1;
}else
{
return 0;
}
}
}
});
int i;
for(i=0; i<ele.length; i++)
{
if(ele[i].w<=rc)
{
ele[i].x=1; //安排
rc-=ele[i].w;
optw+=ele[i].w;
optv+=ele[i].v;
}
else
{
break;
}
}
if(i<ele.length)
{
ele[i].x=rc/ele[i].w;
optw+=ele[i].w*ele[i].x;
optv+=ele[i].v*ele[i].x;
rc-=ele[i].w*ele[i].x;
}
}
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("optw="+optw);
fout.newLine();
fout.write("optv="+optv);
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("w:\t"+ele[i].w);
fout.newLine();
fout.write("v:\t"+ele[i].v);
fout.newLine();
fout.write("x:\t"+ele[i].x);
fout.newLine();
fout.write("+++++++++++++++++++");
fout.newLine();
}
fout.flush();
}
}
四 运行结果
五 总结收获
六 不足
标签:++ gradient 贪心 ret over params family repeat col
原文地址:https://www.cnblogs.com/Howbin/p/9921956.html