To prove safety offer- face questions 14- cut the rope - Dynamic Programming

/*
topic:
	Given a string of length n, cutting the rope segment is m, (n> 1, m> 1)
	Selecting the maximum value of the product of the rope segments.
*/
/*
Ideas:
	Dynamic Programming.
	f(n)=max(f(1)*f(n-1),f(2)*f(n-2),f(3)*f(n-3),...,f(n/2)*f(n-n/2))。
	The optimal solution.
	Big problem can be decomposed into a number of small problems.
	Solution big question depends on a small problem solution.
	Top-down analysis of the problem, problem solving upwardly from the bottom.
*/
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int cutRope(int number){
    if(number <= 1){
        throw("invalid parameter");
    }
    if(number == 2 || number == 3){
        return number-1;
    }
    int* maxProduct = new int[number+1];
    memset(maxProduct,0,number+1);
    maxProduct[1] = 1;
    maxProduct[2] = 2;
    maxProduct[3] = 3;
    int max = 0;
    for (int len ​​= 4, only the <= number, only ++) {
        max = 0;
        for(int left = 1; left <= len / 2; left++){
            cout<<len<<" "<<left<<" "<<len-left<<endl;

            int product =  maxProduct[left] * maxProduct[len-left];
            if(max < product){
                max = product;
            }
        }
        maxProduct[len] = max;
        //cout<<maxProduct[len]<<endl;
    }
    max = maxProduct[number];
    delete[] maxProduct;
    return max;
}


int main () {
    cout<<cutRope(8)<<endl;
}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11845540.html
Recommended