回溯算法之0-1背包问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SeqListSort
{
    /// <summary>
    /// <ather>
    /// lihonglin
    /// </ather>
    /// <content>
    /// 问题描述:有n件物品和一个容量为c的背包。第i件物品的价值是v[i],重量是w[i]。求解将哪些物品装入
    /// 背包可使价值总和最大。在装入背包时,每种物品i只有两种选择,装入或者不装入,既不能装入多次,
    /// 也不能只装入一部分。因此,此问题称为0-1背包问题
    /// 背包问题可看做是一种回溯: 每个包是一个节点, 节点共有2个候选值0、1 。 0代表不放人背包中, 1代表放入背包中。
    /// </content>
    /// </summary>
    class Knapsack
    {
        static int n = 5;//物品数量
        static int c = 10;//背包容量
        static int[] weight = new int[] { 2, 2, 6, 5, 5 };// 各个物品的重量
        static int[] value = new int[] { 6, 3, 5, 4, 6 };//各个物品的价值

        static int max = 0; //max:记录最大价值
        static int[] a = new int[n];//数组存放当前解 各物品选取情况
        //a[i]=0表示不选第i件物品,a[i]=1表示选第i件物品


        static void CheckMax()
        {
            int i = 0;
            int curWeight = 0;//当前物品的重量
            int curValue = 0;//当前物品的价值
            for (i = 0; i < n; i++)
            {
                if (a[i] == 1) //如果选取了该物品
                {
                    curWeight += weight[i]; //累加重量
                    curValue += value[i]; //累加价值
                }
            }
            if (curWeight <= c) //若为可行解
                if (curValue > max) //且价值大于max
                {
                    max = curValue; //替换max
                }
        }

        public static void Search(int m)
        {

            if (m >= n)
                CheckMax(); //检查当前解是否是可行解,若是则把它的价值与max比较
            else
            {

                a[m] = 1; //选则第m件物品
                Search(m + 1); //递归搜索下一件物品
                a[m] = 0; //不选第m件物品
                Search(m + 1); //递归搜索下一件物品
            }
        }

        public static void PrintResult()
        {
            Console.WriteLine("最大价值 " + max);
        }
    }
}

 

转载于:https://www.cnblogs.com/lihonglin2016/p/4307863.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值