代码:
二维数组写法:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt();// 背包容量 int b = scanner.nextInt();// 物品数量 int abs[][] = new int[b + 1][a + 1]; int wp[][] = new int[b + 1][2]; for (int i = 1; i <=b; i++) { wp[i][0] = scanner.nextInt();// 体积 wp[i][1] = scanner.nextInt();// 价值 } for (int i = 1; i <= b; i++) { for (int j = 1; j <= a; j++) { if (wp[i][0] > j) { abs[i][j] = abs[i - 1][j]; } else { abs[i][j] = Math.max(abs[i - 1][j], wp[i][1] + abs[i][j - wp[i][0]]); } } } System.out.println("max=" + abs[b][a]); } }
一维数组写法:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); int abs[] = new int[a + 5]; for (int i = 1; i <= b; i++) { int m = scanner.nextInt();// 体积 int n = scanner.nextInt();// 价值 for (int j = m; j<=a; j++) { abs[j] = Math.max(Math.max(j/m*n, abs[j - m] + n), abs[j]); } } System.out.println("max="+abs[a]); } }
0.0分
0 人评分
WU-C语言程序设计教程(第三版)课后习题11.12 (C++代码)(想学链表的小伙伴可以看看)浏览:964 |
C语言程序设计教程(第三版)课后习题8.8 (C语言代码)浏览:895 |
水仙花 (C语言代码)浏览:1163 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:524 |
陈教主的三角形 (C语言代码)浏览:1196 |
筛排处理 (C语言代码)浏览:830 |
拆分位数 (C语言代码)浏览:464 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:477 |
三进制小数 (C语言代码)浏览:903 |
半数集问题 (C语言代码)浏览:968 |