华为OD C卷 虚拟游戏理财
暴力枚举法。更好的方法是动态规划。菜鸡不会。
自己也写了,但是不全对,gpt写的,但是也有问题。自己修改后正确:
import java.util.*; public class InvestmentGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); // 产品数 int totalInvestment = scanner.nextInt(); // 总投资额 int totalRisk = scanner.nextInt(); // 可接受的总风险 int[] returns = new int[m]; // 产品投资回报率序列 int[] risks = new int[m]; // 产品风险值序列 int[] maxInvestments = new int[m]; // 最大投资额度序列 for (int i = 0; i < m; i++) { returns[i] = scanner.nextInt(); } for (int i = 0; i < m; i++) { risks[i] = scanner.nextInt(); } for (int i = 0; i < m; i++) { maxInvestments[i] = scanner.nextInt(); } List<Integer> result = optimizeInvestment(m, totalInvestment, totalRisk, returns, risks, maxInvestments); for (Integer investment : result) { System.out.print(investment + " "); } } public static List<Integer> optimizeInvestment(int m, int totalInvestment, int totalRisk, int[] returns, int[] risks, int[] maxInvestments) { List<Integer> result = new ArrayList<>(); int maxReturn = 0; int[] bestInvestments = new int[m]; for (int i = 0; i < m; i++) { for (int j = i + 1; j < m; j++) { for (int invest1 = 0; invest1 <= maxInvestments[i]; invest1++) { for (int invest2 = 0; invest2 <= maxInvestments[j]; invest2++) { if (risks[i] + risks[j] <= totalRisk && invest1 + invest2 <= totalInvestment) { int totalReturn = invest1 * returns[i] + invest2 * returns[j]; if (totalReturn > maxReturn) { bestInvestments = new int[m]; maxReturn = totalReturn; bestInvestments[i] = invest1; bestInvestments[j] = invest2; } } } } } } for (int investment : bestInvestments) { result.add(investment); } return result; } }
输入为:
5 100 10
10 20 30 40 50
3 4 5 6 10
20 30 20 40 30
输出为:
0 30 0 40 0