hamster


私信TA

用户名:hamster992

访问量:1784

签 名:

哒哒哒哒哒打字人

等  级
排  名 2841
经  验 2047
参赛次数 1
文章发表 3
年  龄 21
在职情况 学生
学  校 桂林理工大学
专  业 网络工程

  自我简介:

解题思路:经典的01背包解法,比较简单

注意事项:这里使用了逆序的一维dp数组来存放价值结果,需要小心的是dp的大小是比钱的数量多一位的,比较方便观察,要注意将01背包问题中的value改为value*重要程度。这里创建购买物品的类时没有把重要程度作为对象属性输入,个人认为这样比较简洁。

参考代码:

import java.util.Scanner;
import java.util.ArrayList;
public class Main {

    public static void main(String[] args){
    	Scanner scan = new Scanner(System.in);
    	String[] input = scan.nextLine().split(" ");
    	int Money = Integer.parseInt(input[0]);
    	int Number = Integer.parseInt(input[1]);
    	ArrayList<buy> a = new ArrayList<buy>();
    	for (int i = 0; i < Number; i++) {
    		input = scan.nextLine().split(" ");
    		a.add(new buy(Integer.parseInt(input[0]),Integer.parseInt(input[1])));
    	}
    	scan.close();
    	System.out.println(shop(Money,Number,a));
    	
    }//main
    public static int shop(int m,int n,ArrayList<buy> a) {
    	int[] dp = new int[m+1];
    	for (int i = 1; i < n+1; i++) {
    		for (int j = m; j > a.get(i-1).money; j--) {
    			dp[j] = Math.max(dp[j], dp[j-a.get(i-1).money] + a.get(i-1).value);		
    		}
    	}
    	return dp[m];
    }
}//Class Main
	class buy {
		int money;
		int value;
		buy(int a,int b){
			this.money = a;
			this.value = a * b;
		}
	}


 

0.0分

3 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区