动态规划算法
package algorithm; public class T7_21 { public static void main(String[] args){ int s[] = {2,3,4,5}; int v[] = {3,4,5,7}; int C = 9; 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++){ if(j<s[i-1]){ V[i][j] = V[i-1][j]; } else { 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-12 19:45:21