01背包问题·

(只是笔记而已)

有 N 件物品和一个容量是 V 的背包。每件物品只能使用一次。

第 i 件物品的体积是 vi,价值是 wi。

求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。

输出最大价值。

附上java代码吧

import java.util.*;

public class bag {
    public static class costom{
        int weight;//商品质量
        int value;//商品价值
    }
    public static List<costom> c=new ArrayList<costom>();
    public static Scanner sc= new Scanner(System.in);
    public  static int n;
    public  static  int w;
    public static void input(){
        String str1=sc.next().toString();
        String[]nums1=str1.split(",");
        n=Integer.parseInt(nums1[0]);
        w=Integer.parseInt(nums1[1]);
    for(int i=0;i<n;i++){
        costom b=new costom();
        String str=sc.next().toString();
        String[] nums = str.split(",") ;
        b.weight=Integer.parseInt(nums[0]);
        b.value=Integer.parseInt(nums[1]);
        c.add(b);
    }
    }
    public  static void test(){
        Iterator<costom> it = c.iterator();
        while(it.hasNext()){
            int s=it.next().weight;
            System.out.println(s);
        }
    }

    public static int bag01(){
        int [][]aa=new int[n+1][w+1];
       for(int i=1;i<=n;i++){
           for(int j=1;j<=w;j++){
               if(j>=c.get(i-1).weight) {
                   aa[i][j] = Math.max(aa[i - 1][j], aa[i - 1][j - c.get(i - 1).weight] + c.get(i - 1).value);
               }
               else{aa[i][j]=aa[i-1][j];}
           }
       }
       return aa[n][w];
    }
    public static void main(String[]args){
     input();
     //test();
     System.out.println(bag01());
    }
}

视频教会:
01背包讲解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值