多重背包问题java实现

动态规划思想

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
	        
        int N = input.nextInt();// 输入物品个数
        int V = input.nextInt();// 输入背包容量数
        
        int[] v = new int[N+1];// 物品的体积数组
        int[] w = new int[N+1];// 物品的价值数组
        
        int[][] f = new int[N+1][V+1];// 备忘录
        
        // 循环输入物品的体积和价值
        for (int i = 1; i <= N; i++) {
            v[i] = input.nextInt();
            w[i] = input.nextInt();
        }
        
        for (int i = 1; i <= N; i++) { // 现在考虑第i个物品
        	for (int j = 0; j <= V; j++ ) {// 背包容量从0开始
        		f[i][j] = f[i-1][j];
        		if (j >= v[i]) {
        			f[i][j] = Math.max(f[i][j], f[i-1][j-v[i]] + w[i]);
        		} 		
        	}       	
        }
        
        int max = 0;
        for (int i = 0; i <= V; i++) {
        	max = Math.max(max, f[N][i]);
        }
        System.out.println(max);

	}

}


你可能感兴趣的:(Java)