只需要把初始值设为正无穷就行了
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int wi[][]=new int[11][2]; for (int i = 1; i <= 10; i++) { wi[i][0]=sc.nextInt();//价值 wi[i][1]=i;//重量 } int p=sc.nextInt(); int dp[][] =new int[11][p+1]; Arrays.fill(dp[0], (int) (1f/0f)); for (int i = 1; i <= 10; i++) { for (int j = 1; j <= p; j++) { if (wi[i][1]>j) { dp[i][j]=dp[i-1][j]; }else { dp[i][j]=Math.min(dp[i-1][j], dp[i][j-wi[i][1]]+wi[i][0]); } } } System.out.println(dp[10][p]); } }
0.0分
4 人评分