題目:
思路:01揹包的變形。
T代表總共能夠用來採藥的時間,相當於揹包容量。M 代表山洞裏的草藥的數目,相當於物品數量。
代碼:
package Donggui;
import java.util.Scanner;
public class LG採藥 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();//能用的總時間
int m=sc.nextInt();//藥的數量
int[] w=new int[m+1];//每個藥的時間
int[] v=new int[m+1];//每個藥的價值
for (int i = 1; i <= m; i++) {
w[i]=sc.nextInt();
v[i]=sc.nextInt();
}
System.out.println(dp(m,t,w,v));
}
private static int dp(int m,int t,int w[],int v[]) {
int[][] dp=new int[m+1][t+1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= t; j++) {
if (j>=w[i]){
dp[i][j]=Math.max(v[i]+dp[i-1][j-w[i]],dp[i-1][j]);
}else
dp[i][j]=dp[i-1][j];
}
}
return dp[m][t];
}
}