import java.util.Scanner; public class Application { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int v = scanner.nextInt(); // 背包容量 int numOfgoods = scanner.nextInt(); int[] cost = new int[numOfgoods]; int[] value = new int[numOfgoods]; for(int i =0;i<numOfgoods;i++){ cost[i] = scanner.nextInt(); //物品重量 eg: 2 3 4 5 1 } for(int i =0;i<numOfgoods;i++){ value[i] = scanner.nextInt(); //物品价值 eg: 5 6 3 7 2 } zeroonepack(v,cost,value); } public static void zeroonepack(int v, int[] costs,int[] values){ int[] f = new int[v+1]; for(int i=0,items =costs.length;i< items;i++){ for(int j=v;j>=0;j--){ if(j>=costs[i]) f[j] = Integer.max(f[j],f[j-costs[i]]+values[i]); } } System.out.print(f[v]); } }
01背包Java代码
最新推荐文章于 2023-10-15 16:23:14 发布