【回溯法】01背包问题——求最大价值路径

文章介绍了如何运用回溯法(DFS)解决01背包问题,目标是找到使总价值最大的物品组合,不超过背包容量。代码示例展示了Java实现的详细过程,包括物品编号、重量、价值、背包容量等关键变量,以及如何记录和更新最大价值及其对应物品路径。
摘要由CSDN通过智能技术生成

【回溯法】01背包问题——求最大价值路径

题目描述

给定n种物品,背包的容量是c,物品i的重量是wi,其价值为vi。应如何选择装入背包的物品(不是问最大的总价值是多少),使得装入背包中物品的总价值最大?

示例

输入描述:
	个数n	容量c
	重量1,重量2,......
	价值1,价值2,......
输出:
	总价值
	对应的物品编号

输入:
	4
	8
	2 3 4 5
	3 4 5 6
输出:
	10
	2 4

思路

回溯法,dfs遍历各种可能,记录当前价值curValue和当前最大价值bestValue。
当dfs访问超过物品编号范围时,比较curValue和bestValue的值,更新最大价值和最大价值对应的物品列表。
当dfs访问在正常的物品编号范围时,分为
	1、加入当前物品(需要判断加入后会不会大于背包容量)	
	2、不加入当前物品

代码

public class backpack01 {
    static int n;
    static int c;   //容量
    static int []w; //重量
    static int []v; //价值
    static int []visited;   //是否装入
    static int []best;  //记录当前最大价值对应的路径
    static int bestValue = 0, curValue = 0, curWeight = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        c = sc.nextInt();
        w = new int[n+1];
        v = new int[n+1];
        visited = new int[n+1];
        best = new int[n+1];
        for(int i = 1;i <= n;++i){
            w[i] = sc.nextInt();
        }
        for(int i = 1;i <= n;++i){
            v[i] = sc.nextInt();
        }
        for(int i = 0;i <= n;++i){
            visited[i] = 0;
            best[i] = 0;
        }
        dfs(1);
        System.out.println("最大值:" + bestValue);
        System.out.println("最优解: ");
        for (int i=0;i<=n;++i){
            if (best[i] != 0) {
                System.out.print(i + " ");
            }
        }
    }

    static void dfs(int d) {
        if (d > n) {
            if (curValue > bestValue) {
                bestValue = curValue;
                for (int i = 0; i <= n; ++i) { //记录所有路过的节点
                    best[i] = visited[i];
                }
            }
        }
        else {
            //不放入背包
            visited[d] = 0;
            dfs(d+1);
            //放入背包(并且能放入)
            visited[d] = 1;
            if(curWeight + w[d] <= c){
                curWeight += w[d];
                curValue += v[d];
                dfs(d+1);
                curWeight -= w[d];
                curValue -= v[d];
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值