import java.util.ArrayList;
import java.util.Scanner;
class Goods
{
public int weight;
public int value;
public Goods(int weight,int value)
{
this.weight=weight;
this.value=value;
}
}
public class Main2
{
public static void initArray(int[][] c)
{
for(int i=0;i<c.length;i++)
{
for(int j=0;j < c[0].length;j++)
{
c[i][j]=0;
}
}
}
/**
* 获得所选择物品的列表
* @param c
* @param goods
* @param goodsNum
* @param weightOfCar
*/
public static ArrayList<Integer> getSelectedItemsIndex(int[][] c,ArrayList<Goods> goods,int goodsNum,int weightOfCar)
{
ArrayList<Integer> selectedIndex = new ArrayList<>();
int remain_space = weightOfCar;
for(int i=goodsNum ;i>=1;i--)
{
if(remain_space >= goods.get(i).weight)
{
if(c[i][remain_space] - c[i-1][remain_space-goods.get(i).weight] == goods.get(i).value)
{
selectedIndex.add(i);
// System.out.println("goods "+i+" is selected!");
remain_space -= goods.get(i).weight;
}
}
}
return selectedIndex;
}
/**
* 求得最大价值
* @param goods
* @param goodsNum
* @param weightOfCar
* @return
*/
public static int dp(int[][] c,
ArrayList<Goods> goods,//初始物品信息
int goodsNum,//物品个数
int weightOfCar//背包容量
)
{
//初始没有物品的时候价值为0
for(int w=1;w<weightOfCar;w++)
{
c[0][w]=0;
}
for(int i=1;i<=goodsNum;i++)
{
// 背包容量为0时,最大价值为0
c[i][0] = 0;
for(int w =1;w<=weightOfCar;w++)
{
//当前物品i的质量<=w,进行选择
if(goods.get(i).weight <= w)
{
if(goods.get(i).value + c[i-1][w-goods.get(i).weight] > c[i-1][w])
{
c[i][w] = goods.get(i).value + c[i-1][w-goods.get(i).weight];
// System.out.println(goods.get(i).value+","+c[i-1][w-goods.get(i).weight]+","+c[i-1][w]);
}
else
{
c[i][w] = c[i-1][w];
}
}
//当前物品i的重量>w,不选择
else
{
c[i][w] = c[i-1][w];
}
// System.out.println("c["+i+"]["+w+"]"+"="+c[i][w]);
}
}
return c[goodsNum][weightOfCar];
}
public static void main(String[] args)
{
Scanner scanner =new Scanner(System.in);
ArrayList<Goods> goods =new ArrayList<>();
goods.add(new Goods(0, 0));
String[] str = scanner.nextLine().split(" ");
for(int i=0;i < str.length ;i++)
{
int num=Integer.parseInt(str[i]);
goods.add(new Goods(num, num));
}
int carsNum = 0;
while(goods.size()-1 != 0)
{
//物品的个数
int goodsNum = goods.size()-1;
//背包的容量
int weightOfCar = 300;
//the array to save max_value
int[][] c =new int[goodsNum+1][weightOfCar+1];
int max_value = dp(c,goods, goodsNum, weightOfCar);
ArrayList<Integer> selectedIndex = getSelectedItemsIndex(c, goods, goodsNum, weightOfCar);
for (Integer integer : selectedIndex) {
goods.remove(integer.intValue());
}
carsNum++;
}
System.out.println(carsNum);
}
}
动态规划练习题
最新推荐文章于 2021-04-15 23:30:46 发布