"Basic algorithm" cutting steel pipe and dynamic planning

Source: Internet
Author: User

Although the sorting algorithm still has a lot to say, but because this article is already ready to go, first on this, and then back to the sort of a supplement.

Good start ~bigmoyan has a good base friend called Mr. Zou, Mr. Zou in addition to Bigmoyan in the school's community boss, is also a special for the nightclub to provide steel pipe Company's regional manager. Recently, Zou Manager found such a thing, the nightclub needs a variety of lengths of steel pipe for various purposes, but the price of each length of steel pipe is not the same, in summary the following table.

Once upon a time, Zou Manager is always silly to send the head office 10m long steel pipe to 25 pieces of the price to sell, but one day he and the school of the dishes aunt talk about life and career, playing vegetables aunt but came a sentence:

"Obviously each pipe can sell 27 yuan, you only sell 25, learn C + +?" ”

This deeply hurt the Zou manager's mind, so he asked his roommate Jie for help.

The following is an analysis of Bigmoyan Jie:

First of all, we formally express this problem, there is a section of the length of the steel pipe, the entire sale of the price of Pi, to find the appropriate cutting bar scheme makes the most profit. To make it easier for Zou to understand the problem, jie a simple explanation with an example.

For example, you now have a pipe length of 4m, if the whole paragraph sold, sell 9 dollars. However, you can also cut into two sections of 2m steel pipe sold separately, so that altogether can sell 5*2=10 block, so not the whole paragraph will certainly benefit the most. Let's say that for a steel tube that is long I, the most profitable selling price is RI, and we try to do a poor lift.

1 steel pipe, i=1, can only be sold for the whole segment, r1=1

2 steel pipe, i=2, it is easy to find the entire sale of the highest benefit, r2=2

...

4 steel pipe, i=4, the above analysis should be cut into two segments, r4=10=5+5

5 steel pipe, the whole sale is 10 pieces, divided into 1+4, because r4=10, so can sell 11 pieces, divided into 2+3, can sell 13 pieces, so r5=2+3=13

...

Because Jie saw Bigmoyan about the quick sort of introduction, by the division of the impact of the strategy, so Jie just started to think that this is a recursive solution, for the long as I steel pipe, the maximum benefit is:

Ri= MAX{PN, R1+rn-1,r2+rn-2,... RI-1+R1}

This means that, in order to get RI, we can divide the steel pipe into two segments of I, each of which is a matter of great benefit, as Bigmoyan once said, to understand recursion, first of all, you have to understand recursion. Then find the largest one in various sub-methods, nature is the result. Note that the first parameter PN in the above formula is the price of the entire segment sold.

Jie thought told Bigmoyan,bigmoyan soon for Zou wrote such a program (yes I was such a loyal person), written in C + + is probably the following (Bigmoyan with the most is still python, unfortunately Python did not do tail recursion optimization , you can only temporarily use a C + +):

#include <iostream>using namespacestd;intMax (intIintj) {    returnI>j?I:j;} intCut_rod (intP[],intN) {    if(n==0)        return 0; intf=0; intq=-1;  for(intI=1; i!=n;i++) {f=max (p[n-1],cut_rod (p,i) +cut_rod (p,n-i)); Q=Max (q,f); }    returnq;}intMain () {intp[Ten]={1,5,8,9,Ten, -, -, -, -, -}; intF=cut_rod (P,Ten); cout<<F; return 1; } 

The usual, do not panic in the code, take an example of a little analysis, such as the length of the 5 steel pipe for the maximum benefit. Call function Cut_rod (p,5)

After the if test fails, enter the For loop

I=1:

F=max (P[4],cut_rod (p,1) +cut_rod (p,4));

Find out the p[4] and Cut_rod (p,1) +cut_rod (p,4), the former is the price of the whole paragraph 5m steel pipe sale (subscript starting from 0 so is 5-1=4), the latter will be 5m divided into 1m and 4m, two segments of the maximum revenue added up as the maximum revenue for the 1+4 division.

Q=max (Q,F);

The first trip q=-1, so at this time q=f save the 1+4 split when the maximum benefit.

i=2:

F=max (P[4],cut_rod (p,1) +cut_rod (p,4));

As above, this is looking for the whole segment of the sale and 2+3 split between the largest income between the big person.

Q=max (Q,F);

Q When I last saved F, this time compare the new F with the last value (q) and take the biggest profit

Back and so on

However, when testing the code Bigmoyan found that the code execution efficiency too he meow low! n larger time, basically n increase 1, code run time will add twice times, I dare to test a 500m long steel pipe of the maximum benefit (assuming the data have), estimated Zou Manager will graduate.

A little analysis found that the reason for the low execution efficiency is that the sub-problem has been repeated calculation! Calculate the profit of 10m steel pipe when the profit of 1~9m is counted once, and in order to calculate the profit of 9m steel pipe, I have to calculate the 1~8m again.

Heart! Good! Tired!

At this point, the smart Jie has also been aware of the problem, the problem seems to be recursive, in fact, and recursion slightly different. Recursive sub-problems do not intersect with each other, and the sub-problem of this thing is intersecting, the same sub-problem is calculated over and over again, which leads to inefficient efficiency.

Jie a little thought, stratagem, since the sub-problem is calculated over and over again, we do not use space for time, the results of the sub-problem has been calculated to save, when the need for the first query, if the problem has been calculated, directly to use is, if not calculated.

Bigmoyan simply astounding, rewrite the code again, then there is the following C + + code:

NT Cut_rod (int p[],int  n) {    int *r=newint[n];       for (int i=0; i!=n;i++)        r[i]=-1;     return Cut_rod_memo (p,n,r);}

Calling function names is consistent and easy to understand, first set up a memo r,r to save the answers to the sub-problems that have been calculated. Initialize it to-1. We still take the calculation of 5m steel pipe as an example, then R is initialized to [ -1,-1,-1,-1,-1].

Then call Cut_rod_memo to calculate the maximum benefit, so what is Cut_rod_memo?

NT Cut_rod_memo (intP[],intNintr[]) {    if(r[n-1]>=0)        returnr[n-1]; if(n==0)        intq=0; Else{        intf=0; intq=-1;  for(intI=1; i!=n;i++) {f=max (p[n-1],cut_rod_memo (p,i,r) +cut_rod_memo (p,n-i,r)); Q=Max (q,f); } r[n-1]=Q; returnQ; }}

OK, don't head big, Bigmoyan slowly analysis.

After entering the Cut_rod_memo, the first query 5m results is not already calculated, the answer is of course no, r[4]=-1. Then into the Else statement, where the statement is the same as the previous recursive version, the difference is only the recursive call is Cut_rod_memo, because the first statement in the function is to determine whether the answer to the sub-problem is not done well, so to avoid multiple calculations of the same sub-problem, the following show this process.

I=1:

From the previous version of the No-brain recursion, the for loop solves the maximum benefit of i=1 when the For loop is complete and saves it in R[0], at which point R[0]=1

i=2:

In recursive call Cut_rod_memo (p,1,r), because it is already good r[0]=1, so cut_rod_memo the first if judgment succeeds, return r[0], at this time the return value is calculated by the results of the direct take out, no recalculation.

Other things in the same vein.

Bigmoyan and Jie two opposite and smile, smile is full of praise to each other. Together they came to Zou manager of Silver Birch Canteen, and playing vegetables aunt such a talk, this hope to receive aunt praise eyes, didn't think aunt put a spoon in the dish shake off some, indifferent said:

Well This is not dynamic planning, what fresh things, worth the wave, swipe! ”

Ps. Dynamic programming problems of course, not only this category, but the basic idea is consistent, is not to solve the problem has been solved, interested students can Baidu a bit of dynamic planning

PPS: The following is all C + + code

1#include <iostream>2 using namespacestd;3 4 intMax (intIintj) {5     returnI>j?i:j;6 } 7 8 intCut_rod_memo (intP[],intNintr[]) {9     if(r[n-1]>=0)Ten         returnr[n-1]; One     if(n==0) A         intq=0; -     Else{ -         intf=0; the         intq=-1; -          for(intI=1; i!=n;i++){ -F=max (p[n-1],cut_rod_memo (p,i,r) +cut_rod_memo (p,n-i,r)); -q=Max (q,f); +         } -r[n-1]=Q; +     returnQ; A     } at } -  - intCut_rod (intP[],intN) { -     int*r=New int[n]; -      for(intI=0; i!=n;i++) -r[i]=-1; in     returnCut_rod_memo (p,n,r); - } to  + intMain () { -     intp[Ten]={1,5,8,9,Ten, -, -, -, -, -}; the     intF=cut_rod (P,Ten); *cout<<F; $     return 1;Panax Notoginseng}

"Basic algorithm" cutting steel pipe and dynamic planning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.