360笔试编程卖粉笔问题解答
简单阐述一下题目变量:
有彩色粉笔 n 个;
有白色粉笔 m 个;
把 a 个彩色粉笔盒 b 个白色粉笔打包可以买 x 元:(a彩 + b白) -> x元
把 c 个白色粉笔打包可以卖 y 元: c白 -> y元
把 d 个彩色粉笔打包可以卖 z 元: d 彩 -> z元
题目即是一个动态规划问题,设 dp[i][j] 表示当我们有 i 个彩色粉笔和 j 个白色粉笔的时候最多可以卖多少元,那么我们考虑三种情况:
S1、只卖白色: dp[i][j] = y + dp[i][j-c]
S2、只卖彩色: dp[i][j] = z + dp[i-d][j]
S3、混合出售: dp[i][j] = x + dp[i-a][j-b]
即我们取三种情况的最大值: d[i][j] = MAX(S1,S2,S3);
那么 d[n][m] 就是题目的解
public static void main(String ...args){
Scanner in = new Scanner(System.in);
String[] line = in.nextLine().split(" ");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
line = in.nextLine().split(" ");
int a = Integer.parseInt(line[0]);
int b = Integer.parseInt(line[1]);
int c = Integer.parseInt(line[2]);
int d = Integer.parseInt(line[3]);
line = in.nextLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
int z = Integer.parseInt(line[2]);
int[][] money = new int[n+1][m+1];
for(int i = 0; i <= n; i++){
for(int j = 0; j <= m; j++){
int white = 0;
int color = 0;
int colorWhite = 0;
if(j < c){
white = 0;
}else{
white = y + money[i][j-c];
}
if(i < d){
color = 0;
}else{
color = z + money[i-d][j];
}
if(i < a || j < b){
colorWhite = 0;
}else{
colorWhite = x + money[i-a][j-b];
}
money[i][j] = Math.max(Math.max(color, white), colorWhite);
}
}
System.out.println(money[n][m]);
}
海康威视公司福利 1107人发布