POJ3624
来源:互联网 发布:淘宝分流最多设置多少 编辑:程序博客网 时间:2024/06/05 19:32
0-1背包,动态规划学习
import java.io.FileNotFoundException;import java.util.Scanner;public class Main {//Memory Limit Exceeded static int r; static int c; static int[] w; static int[] v; // static int mv[][];//max value static int[][] mv; public static void main(String[] args) throws FileNotFoundException { // File file=new File("c:/data.txt"); // Scanner cin=new Scanner(file); Scanner cin = new Scanner(System.in); r = cin.nextInt();// r件物品 c = cin.nextInt();// 袋子大小 mv = new int[r + 1][c + 1]; w = new int[r + 1];// 第i件物品的重量 v = new int[r + 1];// 第i件物品的价值 for (int i = 1; i <= r; i++) {// input weight & value w[i] = cin.nextInt(); v[i] = cin.nextInt(); } for (int i = 1; i <= r; i++) { for (int j = 1; j <= c; j++) {// j袋子剩余容量 if (j >= w[i]) {// 装得下 int a = mv[i - 1][j];// 不装第i件物品 int b = mv[i - 1][j - w[i]] + v[i];// 装第i件物品 mv[i][j] = max(a, b); } else { mv[i][j] = mv[i - 1][j]; } } } System.out.println(mv[r][c]); } static int max(int a, int b) { return a > b ? a : b; }}
优化空间
import java.io.FileNotFoundException;import java.util.Scanner;public class Main {//poj上类名必须为Main static int r; static int c; static int[] w; static int[] v; // static int mv[][];//max value static int[] mv; public static void main(String[] args) throws FileNotFoundException { // File file=new File("c:/data.txt"); // Scanner cin=new Scanner(file); Scanner cin = new Scanner(System.in); r = cin.nextInt();// r件物品 c = cin.nextInt();// 袋子大小 mv = new int[c + 1]; w = new int[r + 1];// 第i件物品的重量 v = new int[r + 1];// 第i件物品的价值 for (int i = 1; i <= r; i++) {// input weight & value w[i] = cin.nextInt(); v[i] = cin.nextInt(); } for (int i = 1; i <= r; ++i) { for (int j = c; j >= w[i]; --j) {// j袋子剩余容量 int a = mv[j - w[i]] + v[i];// 加上第i件物品的最大价值 int b = mv[j];// 不加第i件物品的最大价值 mv[j] = max(a, b); } } System.out.println(mv[c]); } static int max(int a, int b) { return a > b ? a : b; }}
0 0
- POJ3624
- poj3624
- poj3624
- poj3624
- poj3624
- poj3624
- poj3624
- POJ3624
- poj3624
- poj3624
- poj3624
- POJ3624
- poj3624
- poj3624
- poj3624
- poj3624 Charm Bracelet
- POJ3624解题报告
- poj3624 Charm Bracelet
- GPS小程序
- Windows 函数调用
- NSThread - 2
- rest api请求时token的注入
- IT培训新模式——在线教育
- POJ3624
- 8_25 设置用户id或组id的程序绝对不能再调用system函数。安全漏洞
- JS实现货币格式化、货币繁体汉字化
- nginx与HA
- Eclipse转IDEA遇到的问题
- ubuntu下修改yaffs2文件系统镜像文件
- Linux学习20_每天一个linux命令(9):touch 命令
- CodeForces-588A Duff and Meat
- IT成长之路必学技能