package recursion;
import java.util.HashMap;
import java.util.Map;
public class GreedyPackage {
private static int MAX_WEIGHT = 150 ;
private static int [] weights = new int[] {35,30,60,50,40,10,25};
private static int [] values = new int[] {10,40,30,50,35,40,30};
private void packageGreedy(int capacity , int weights[], int values[]) {
int n = weights.length;
double[] r = new double[n];//性价比数组
int index [] = new int[n];//性价比排序物品的下标
for(int i =0;i<n;i++) {
r[i] = (double)values[i]/(double)weights[i];
index[i] = i;//默认排序
}
double temp =0;
for(int i=0;i<n-1;i++) {
for(int j =i+1;j<n;j++) {
//性价比相同,取小的在前
if(r[i]<r[j] || (r[i]==r[j] && weights[i]>weights[j])) {
temp = r[i];
r[i] = r[j];
r[j] = temp;
int x = index[i];
index[i] = index[j];
index[j] = x;
}
}
}
int [] w1 = new int[n];
int [] v1 = new int[n];
for(int i =0;i<n;i++) {
w1[i] = weights[index[i]];
v1[i] = values[index[i]];
}
int [] x = new int[n];//记录是否装进包了
int maxValue = 0;
int maxWeight = 0;
int i =0;
int lastIndex = 0;
while(i<n && w1[i]<capacity) {
capacity -= w1[i];
x[i] = 1;
System.out.println("物品"+w1[i]+"被放进包了");
maxValue += values[i];
maxWeight += weights[i];
lastIndex = i;
i++;
}
//判断背包是否放满了,没有放满的就需要拿出最后的几个进行比较
if(maxWeight<maxWeight+capacity && lastIndex<n-1) {
//减去最后加的元素,并找到合适的元素替换
Map<String,Integer> map = checkAndexchange(w1,v1,x,capacity,maxValue,maxWeight,lastIndex);
if(null != map.get("MaxWeight")) {
maxWeight = map.get("MaxWeight");
maxValue = map.get("MaxValue");
}
}
System.out.println("装进背包的最大价值为"+maxValue+"总重量为"+maxWeight);
}
/**
* 这里仅仅优化了一步,多步优化就类似动态规划算法了
*
* 用最后两个替换最后一个
*
*
* w1 ,v1 是根据性价比排好的
* @param w1 重量数组
* @param v1 价值数组
* @param x 是否已经放进背包
* @param capacity 背包剩余的容量
* @param maxValue 背包里的物品的总价值
* @param maxWeight 背包里的物品的总重量
* @param lastIndex 最后放进背包的元素的下标
*/
private Map<String,Integer> checkAndexchange(int[] w1, int[] v1, int[] x, int capacity, int maxValue,int maxWeight , int lastIndex) {
int value = v1[lastIndex];
int weight = w1[lastIndex];
int tempWeight = w1[lastIndex+1];
int tempValue = v1[lastIndex+1];
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=lastIndex+2;i<x.length;i++) {
if(tempWeight+w1[i]<=weight+capacity && tempValue+v1[i]>value) {
x[lastIndex] = 0;
x[lastIndex+1] = 1;
x[lastIndex+2] = 1;
capacity = capacity+weight -tempWeight-w1[i];
maxValue = maxValue+tempValue+v1[i]-value;
maxWeight = maxWeight - weight+ tempWeight+w1[i];
System.out.println("物品"+w1[lastIndex]+"被拿出包了");
System.out.println("物品"+w1[lastIndex+1]+"被放进包了");
System.out.println("物品"+w1[lastIndex+2]+"被放进包了");
map.put("MaxValue", maxValue);
map.put("MaxWeight", maxWeight);
}
}
return map;
}
public static void main(String[] args) {
GreedyPackage gp = new GreedyPackage();
gp.packageGreedy(MAX_WEIGHT, weights, values);
// gp.packageGreedy(14, new int[] {5,5,7,6}, new int[] {10,10,13,11});
// gp.packageGreedy(20, new int[] {16,10,10}, new int[] {32,19,18});
}
}
贪心算法实例
最新推荐文章于 2020-12-25 14:47:44 发布