背包问题

参考博客:
https://www.cnblogs.com/fengziwei/p/7750849.html

思路都是,先放第一个物品,容量从1到max 的最大收益

1.0-1背包问题
0-1背包问题是指每一种物品都只有一件,可以选择放或者不放。现在假设有n件物品,背包承重为m。

import java.util.Scanner;

/**
 * Created by zfr on 2018/09/07.
 * 完全背包问题,每个物品可以放无数个
 */
public class Main {
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int Max = scanner.nextInt();//背包的容量
        int counts = scanner.nextInt();//总共有多少种东西
        //每个东西的重量和价值
        int[] weights = new int[counts];
        int[] values = new int[counts];
        for(int i = 0 ; i < counts ; i++ ){
            weights[i] = scanner.nextInt();
            values[i] = scanner.nextInt();
        }
        int[][] f = new int[counts+1][Max+1] ;
        for(int i = 1 ; i < counts ; i++){
          //  System.out.println(i);
            for(int j = 1 ; j <= Max;j++){
               // System.out.println(j);
                if(weights[i] > j){//容量不够,不放
                    f[i][j] = f[i-1][j];
                }else {//容量够,选择放或者不放的最大值
                    f[i][j] = Math.max(f[i-1][j] , f[i-1][j - weights[i]] + values[i]);
                }
            }
        }
        System.out.println(f[counts-1][Max]);
    }
}

测试用例:

10
5
2 6
2 3
6 5
5 4
4 6
输出:11

2.完全背包问题
完全背包问题是指每种物品都有无限件。

import java.util.Scanner;

/**
 * Created by zfr on 2018/09/07.
 */
public class Main {
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int Max = scanner.nextInt();//背包的容量
        int counts = scanner.nextInt();//总共有多少种东西
        //每个东西的重量和价值
        int[] weights = new int[counts];
        int[] values = new int[counts];
        for(int i = 0 ; i < counts ; i++ ){
            weights[i] = scanner.nextInt();
            values[i] = scanner.nextInt();
        }
        int[][] f = new int[counts+1][Max+1] ;
        for(int i = 1 ; i < counts ; i++){
            //  System.out.println(i);
            for(int j = 1 ; j <= Max;j++){
                // System.out.println(j);
                if(weights[i] > j){//容量不够,不放
                    f[i][j] = f[i-1][j];
                }else {//容量够,选择不放、放1个...最大值,取最优
                    //放1个或者多个
                    int count = j / weights[i] ;//不放的情况
                    f[i][j] = f[i-1][j] ;
                    for (int k = 1 ; k <= count ; k++ ){
                        f[i][j] = Math.max(f[i][j] , f[i-1][j - k * weights[i]] + k * values[i]);
                    }
                }
            }
        }
        System.out.println(f[counts-1][Max]);
    }
}

10
5
2 6
2 3
6 5
5 4
4 6
输出15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值