To prove safety offer- face questions 14- cut the rope - greedy algorithm

/ * 
Title: 
	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. 
* / 
/ * 
Thinking: 
	greedy algorithm. 
	When the length of rope is greater than 5, as much as possible the shear length of the rope 3; 4 when the rest of the length of the rope, the rope to cut the rope 2 of length two. 
* / 
/ * 
Demonstrated: 
	when n> = 5, 2 (n -2)> n, 3 (n-3)> n, that is, when n is greater than 5, to put it cut length of 2 or 3 rope, and 3 (n-3)> 2 (n-2), it is possible to cut the length of the rope 3. 
	When n = 4, the maximum cut of 2 * 2. 
* / 
#Include <the iostream> 
#include <string.h> 
#include <algorithm> 
#include <math.h> 
the using namespace STD; 
int cutRope (int Number) { 
    IF (Number <=. 1) { 
        the throw ( "invalid Parameter "); 
    } 
    IF (Number Number == == 2 ||. 3) { 
        return-Number. 1; 
    }
    Number timesOf3 = int /. 3; 
	
	// when the remaining length is 4, to cut 2 * 2 
    IF (Number -. 3 * == timesOf3. 1) { 
        timesOf3 -; 
    } 
    int timesOf2 = (Number - timesOf3 *. 3) / 2 ; 
    return (int) (POW (. 3, timesOf3)) * (int) (POW (2, timesOf2)); 
} 


int main () { 
    COUT << cutRope (. 8) << endl; 
}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11845649.html