动态规划算法——钢条切割问题分析

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

namespace 带备忘的自顶向下
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] result = new int[11];
            int[] price = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };//索引为钢条长度
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(UpDown(i, price,result));
            }
        }
        public static int UpDown(int n, int[] p,int[] result) //返回值为最优解
        {
            if (n == 0) return 0;//不能分割时直接返回0
            if (result[n] != 0)
            {
                return result[n];//最优解已经求出的时候不再重新求,直接取值
            }
            int temp = 0;
            for (int i = 1; i <= n; i++)
            {
                int maxPrice = p[i] + UpDown(n - i, p,result);//递归调用,求出n-i的最优解
                if (maxPrice > temp)
                {
                    temp = maxPrice;
                }
            }
            result[n] = temp;//保存最优解
            return temp;
        }
    }
}



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

namespace 自底向上法
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] result = new int[11];
            int[] price = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };//索引为钢条长度
            for (int i = 1; i <= 10; i++)
            {
               Console.WriteLine(BottomUp(i, price, result));
            }
            Console.ReadKey();
        }
       
        public static int BottomUp(int n, int[] p, int[] result)
        {
            for (int i = 1; i <= n; i++)//第一次循环 i=1 第二次循环 i=2
            {
                int temp = 0;
                for (int j = 1; j <= i; j++)
                {//第一次循环 j=1 第二次循环 j=1
                    int maxPrice = p[j] + result[i - j];//第一次循环 i-j=0 result[0]=0
                    if (maxPrice > temp) {
                        temp = maxPrice;//第一次循环 maxprice=1;
                    }
                }
                result[i] = temp;//第一次循环 result[1]=1
            }
            return result[n];
        }
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值