问题描述
我正在为背包中的最大赃物编写代码,其中防盗必须最大化其赃物,他的背包最大容量为9kg 如果有3个元素的权重和值,即5kg-30 /-; 4kg-28 /-; 3kg-24 /-,则输出应为3 8 + 4 7 + 6 * 2 = 64(其中8 = 24/3; 6 = 30/5; 7 = 28/4),请提前感谢我的代码。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements :");
int n = scan.nextInt();
int[] weights = new int[n];
int[] values = new int[n];
System.out.println("Enter the weights of the elemnts :");
for(int i=0;i<n;i++) {
weights[i]=scan.nextInt();
}
System.out.println("Enter the Values of the Elements : ");
for(int i=0;i<n;i++) {
values[i]=scan.nextInt();
}
System.out.println("Enter the value of the weight of the knapsack :");
int knapsack = scan.nextInt();
if(knapsack==0) {System.out.println("error,value must be above 0");}
int[] priorvalue = new int[n];
for(int i=0;i<n;i++) {
priorvalue[i]=(weights[i]/values[i]);
}
Arrays.sort(priorvalue);
int k=(n-1);
int total=0;
int l=0;
while(k<=(n-1) && k>=0) {
for(int i=0;i<n;i++) {
if(priorvalue[k]==(weights[i]/values[i])) {
total = total + (priorvalue[k]*weights[i]);
System.out.println(total);
l=knapsack-weights[i];
}
if(l==0) {break;}
}
k--;
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)