• 算法导论动态规划 15.1-3 钢条切割问题


    算法导论的第一个动态规划问题--钢条切割

    我们知道钢条的长度和价格为:

    长度i 1 2 3 4 5 6 7 8 9 10
    价格pi 1 5 8 9 10 17 17 20 24 30

    书上的两种方法已经很清楚,这里主要说一下课后练习里面15-3钢条成本加上切割成本,即要切割的次数最少。15-4返回切割方案

    #include<fstream>
    #include<iostream>
    using namespace std;
    int main()
    {
    	int const N = 11;
    	int P[N] = { 0,1,5,8,8,10,17,17,20,24,30 }; //钢条长度对应的价格
    	int const length = 7; //待切割的钢条长度
    	int r[length+1] = { 0 },num[length+1] = { 0 };//数组r记录自底向上的每次钢条的最大价格,数组num记录切割次数
    	int s[length + 1] = { 0 };//记录第一段钢条的最优切割长度
    	for (int j = 1; j <= length; j++)
    	{
    		int q = -1,index=0;
    		for (int i = 1; i <= j; i++)
    		{
    			if (q < P[i] + r[j - i])
    			{
    				q = P[i] + r[j - i];
    				index = j - i;
    				s[j] = i;
    			}
    			if (q == P[i] + r[j - i])
    			{
    				if (num[j - i] > num[index])
    				{
    					index = j - i;
    					s[j] = i;
    				}
    			}
    			
    		}
    		if (index == 0) num[j] == 0;
    		else num[j] = num[index] + 1;
    		r[j] = q;
    		
    	}
    //	for (int i = 1; i <= length; i++)
    //	{
    	//	cout << num[i] << endl;
    //	}
    	int n = length;
    	while (n > 0)
    	{
    		cout << s[n] << " ";
    		n = n - s[n];
    	}
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    微信小程序之跨界面传参
    微信小程序简易教程
    css动画与js动画的区别
    不同浏览器兼容性的区别
    Filter学习
    FileDescriptor
    Executor框架
    Struts1的处理流程
    Struts1的实现原理
    [转]TOMCAT原理以及处理HTTP请求的过程、ContextPath ServletPath
  • 原文地址:https://www.cnblogs.com/blairwaldorf/p/9000130.html
Copyright © 2020-2023  润新知