Reduce the rope problem C++

 


Title description

Here is a rope with a length of n. Please cut the rope into m segments of integer length (m and n are integers, n>1 and m>1). The length of each rope is k[0],k [1],...,k[m]. What is the maximum possible product of k[0]xk[1]x...xk[m]? For example, when the length of the rope is 8, we cut it into three pieces with lengths of 2, 3, and 3. The maximum product obtained at this time is 18.

Enter description:

输入一个数n,意义见题面。(2 <= n <= 60)

Output description:

输出答案。

Example 1

enter

8

Output

18

 

answer: 

class Solution {

public:

    int cutRope(int number) {

        if(number==2)

            return 1;

        if(number==3)

            return 2;

        if(number%3==0)

            return pow(3,number/3);

        else if((number-1)%3==0)

            return 4*pow(3,(number-4)/3);

        else

            return 2*pow(3,(number-2)/3);

    }

};

The above is the answer submitted by Niuke at the time.

The following is written in a case statement, which looks more tidy:

#include <iostream>

#include<cmath>

using namespace std;





int f(n){

    switch(1){

        case n=2:

            return 1;

            break;

        case n=3:

            return 2;

            break;

        case n%3 == 0:

            return pow(3,n/3);

            break;

        case (n-1)%3 == 0:

            return 4*pow(3,(n-4)/3);

            break;

        default:

            return return 2*pow(3,(n-2)/3);

            break;

    }

}



int main() {

    int n = 0;

    cin >> n;

    cout << f(n) << endl;

    return 0;

}


The largest multiplier can only be a combination of powers of 2 and 3, just find the corresponding number of 2 or 3. There is no dynamic programming, greedy algorithm.

n=2 and n=3 are special cases, just write them separately.

 

Starting from n=4,

Draw it on paper and draw a dozen numbers to find a pattern:

The power of 2 is a cycle of 2, 1, 0;

 

The power of 3 is determined by the power of 2, so the key to solving the problem is to find the conditions that determine the power of 2.

Then it is found that the power of 2 is 0, the corresponding number is a multiple of 3, the power of 2 is 2, the corresponding number minus 1 is a multiple of 3, and the power of 2 corresponding to the remaining numbers is 1.

List the three situations and calculate them separately.

 


to sum up

It is enough to classify and discuss such issues.

Guess you like

Origin blog.csdn.net/sinat_39416814/article/details/104071817