动态规划算法
package algorithm; public class T7_21 { public static void main(String[] args){ int s[] = {2,3,5,6}; int v[] = {3,4,5,7}; int C =11; System.out.println(big(s,v,C)); } public static int big(int[] s,int [] v,int C){ int L_s = s.length; int V[][] = new int[100][100]; for(int i =0;i<=L_s;i++){ V[i][0] = 0; } for(int j =0;j<=C;j++){ V[0][j] = 0; } for(int i =1;i<=L_s;i++){ for(int j =1;j<=C;j++){ V[i][j] = V[i-1][j]; if(s[i-1]<=j){ V[i][j] = V[i][j]>(V[i-1][j-s[i-1]]+v[i-1])?V[i][j]:(V[i-1][j-s[i-1]]+v[i-1]); } } } for(int i =0;i<=L_s;i++){ for(int j = 0;j<=C;j++){ System.out.printf("%3d",V[i][j]);} System.out.println(); } System.out.print(" 背包的最大价值为:"); return V[L_s][C]; } }
时间: 2024-10-31 05:40:08