多重背包 java实现

package eg.nk_mt;

import java.util.Scanner;

/**
 * 多重背包
 * 多重和完全更接近,多了数量的限制,用一个count[n]计数数组来限制物品i的数量。
 * 当放入第i个物品是较优值的时候,count[i]=count[j-weight[i]]+1(j 的含义:);
 * 这样做是因为,放入第i个物品的操作是基于count[j-weight[i]]放入的,
 * 所以当count[i-weight[i]]>=amount[i]时,就要阻止放入即便放入第i个物品是较优值
 */
public class backpack03 {
    public static void main(String[] args) {
/*        Scanner in = new Scanner(System.in);
        int n = in.nextInt();//物品种类个数
        int [] weight = new int[n];//重量
        int [] value = new int[n];//价值
        for (int i = 0; i < n; i++) {
            weight[i] = in.nextInt();
        }
        for (int i = 0; i < n; i++) {
            value[i] = in.nextInt();
        }
        int target = in.nextInt();//背包容量*/
        int n = 5;
        int [] weight = {5,4,7,2,6};
        int [] value = {12,3,10,3,6};
        int target = 15;
        int [] account = {2,4,6,8,1};//每种物品的数量
        int[] arr = new int[target + 1];
        //依次轮转,把当背包中有一个、二个、三个,,,
        for (int i = 0; i < n; i++) {  // i 表示背包中可以放前(i + 1) 种物品
            // 完全背包问题
            if(weight[i] * account[i] >= target){
                for (int j = weight[i]; j <= target; j++) {  
                    arr[j] = Math.max(arr[j],arr[j - weight[i]] + value[i]);
                }
                return;
            }
            //01背包问题,并使用二进制方法进行优化
            int tmpCount = 1;
            while (tmpCount < account[i]){
                for (int j = target; j >= tmpCount * weight[i]; j--) {  // j 表示当前背包的容量
                    arr[j] = Math.max(arr[j],arr[j - tmpCount * weight[i]] + tmpCount * value[i]);
                }
                account[i] -= tmpCount;
                tmpCount = tmpCount << 1;
            }
            for (int j = target; j >= weight[i]; j--) {  // j 表示当前背包的容量
                arr[j] = Math.max(arr[j],arr[j - weight[i]] + value[i]);
            }
            
        }
        for (int i = 0; i <= target; i++) {
            System.out.print(arr[i] + " ");
        }

    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值