背包问题的非递归算法

        const int M = 12;//背包重M斤   
            int[,] Subjects = {{3,4},{4,5},{5,7},{8,10} };//物件数组,重量/价值            
            int CurrentWeight = 0, CurrentValue = 0;//当前重量,当前价值
            int MaxValue = 0;//最优价值

            for (int i = 0; i < Subjects.GetUpperBound(0)+1; i++)
            {
                CurrentWeight = 0; CurrentValue = 0;
                int j = i;//背包下标               

                while (CurrentWeight < M)
                {                    
                    CurrentWeight += Subjects[j, 0];
                    CurrentValue += Subjects[j, 1];
                  
                    if (CurrentWeight == M)
                    {
                        if (CurrentValue > MaxValue)//找到一个新的最大价值解。
                        {
                            MaxValue = CurrentValue;
                            CurrentValue -= Subjects[j, 1];
                            CurrentWeight -= Subjects[j, 0];                            
                        }

                    }
                    else if (CurrentWeight > M)
                    {
                        CurrentValue -= Subjects[j, 1];
                        CurrentWeight -= Subjects[j, 0];                  
                    
                    }

                    if (j +1< Subjects.GetUpperBound(0)+1)  j++; //开始取下一个值;
                    else break;

                }

              
            }

            Console.Write(MaxValue); //输出最优价值

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值