//贪心问题中最难的了 未完成 甚至有可能贪心解决不了
//一个背包 输入体积 物品种类 个数 体积 价值 求一个最大价值
package com.company.kkk;
import java.io.;
import java.util.;
class imp{
private int m;
private int w;//体积
private int s;
private float value;//单位价值
public imp(int m,int w, int s) {
this.m = m;
this.w = w;
this.s = s;
this.value = s/w;
}
public int getW() {
return w;
}
public float getValue() {
return value;
}
public int getS() {
return s;
}
public void set()
{
this.value=0;
this.w = 0;}
}
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();//物品种类多少
int v = in.nextInt();//背包体积
int sum = 0;
imp[] pac = new imp[n];
for (int i = 0; in.hasNext(); i++) {
pac[i] = new imp(in.nextInt(), in.nextInt(), in.nextInt());
}
while (v >= 0) {
float max = pac[1].getValue();
int num = 0;
for (int i = 0; i < n; i++) {
if (pac[i + 1].getValue() > max) {
max = pac[i + 1].getValue();
num = i;
}
v = v - pac[num].getW();
pac[num].set();
sum += pac[num].getS() * pac[num].getW();
}
}
System.out.println(sum);
}
}
本文探讨了一种经典的贪心算法应用——背包问题。通过实例解析,详细介绍了如何使用贪心策略求解最大价值问题,包括物品的体积、种类、数量及价值的综合考量。代码实现部分展示了Java语言中如何定义物品类并实现贪心算法,通过比较单位价值来选择装入背包的物品。

被折叠的 条评论
为什么被折叠?



