1. 问题描述:
2. 核心思想
提出贪心策略——证明策略正确
3. 算法伪代码
核心算法
3. Java代码实现
// franctionalKnapsack Algorithm
public class franctionalKnapsack {
public static class Goods{
String name;
int weight;
int value;
float valuePerWeight;
public Goods(String name, int weight, int value) {
this.name = name;
if (weight>0){
this.weight = weight;
this.valuePerWeight= (float)value / (float)weight;
}
this.value = value;
}
}
public static void main(String[] args){
Goods[] input = new Goods[5];
input[0] = new Goods("苏打水",600, 60);
input[1] = new Goods("汽水",250,10);
input[2] = new Goods("橙汁",200,36);
input[3] = new Goods("苹果汁",100,16);
input[4] = new Goods("西瓜汁",300, 45);
int result = franctionalKnapsack(input, 800, 5);
System.out.print("最大价值:"+result);
}
private static int franctionalKnapsack(Goods[] goods, int C, int n){
quickSortSimple(goods, 0, goods.length-1);
int i = 0;
int ans = 0;
while(C>0 && i<n){
if(goods[i].weight<=C){
System.out.println("选择商品"+goods[i].name);
ans += goods[i].value;
C -= goods[i].weight;
}else{
System.out.println("选择"+C+"体积的商品"+goods[i].name);
ans += C * goods[i].valuePerWeight;
C = 0;
}
i++;
}
return ans;
}
private static void quickSortSimple(Goods[] A, int l, int r){
Goods temp;
int i=l;
int j=r;
if(l<r){
temp = A[i];
while(i!=j){
while(i<j && A[j].valuePerWeight <= temp.valuePerWeight){
j--;
}
A[i] = A[j];
while(i<j && A[i].valuePerWeight >= temp.valuePerWeight){
i++;
}
A[j] = A[i];
}
A[i] = temp;
quickSortSimple(A, l, i-1);
quickSortSimple(A, i+1,r);
}
}
}