Cut the rope (a greedy algorithm)

. 1 #include <the iostream>
 2 #include <the cmath>
 . 3  
. 4  the using  namespace STD;
 . 5  
. 6  / * *
 . 7  * Title Analysis:
 8  * to name a few examples, can be seen in law.
9  * 4: 2 * 2
 10  * 5: 2 * 3
 . 11  * 6: 3 *
 12 is  * 7: 2 * 2 * 3 or 4 * 3
 13 is  * 8: 2 * 3 * 3
 14  * 9: 3 * 3 * 3
 15  * 10: 2 * 2 * 3 * 3 or 4 * 3 * 3
 16  * 11: 2 * 3 * 3 * 3
 . 17  * 12: 3 * 3 * 3 * 3
 18 is  * 13: 2 * 2 * 3 or 4 * 3 * 3 * 3 * 3 * 3
 . 19  *
 20  * The following is the analysis:
 21 * First determines k [0] to k [m] which may be digital, in fact, can only be 2 or 3.
22  * Of course, there may be 4, but 4 = 2 * 2, we simply those who do not consider them.
23  * 5 <2 * 3,6 <3 * 3, larger than the number 6 we do not have even considered, we must continue to divide.
24  * Second, look at the number 2 and 3, the number 2 is certainly less than three, why? Because 2 * 2 * 2 <3 * 3, then the title is simple.
25  * 3 divided by n directly The remainder is judged from a two or 2 2 2 on the line or not.
26  * Since the predetermined topic m> 1, it is only 2 * 1 * 1 2 3 only, these two special cases directly back on the line.
27  *
 28  * exponentiation complexity is: O (log n), using dynamic programming to do would be more time-consuming.
29   * / 
30  Long  Long n_max_3 ( Long  Long n-) {
 31 is      IF (n-== 2 ) {
 32          return  . 1 ;
 33 is      }
 34 is      IF (n == 3) {
35         return 2;
36     }
37     long long x = n % 3;
38     long long y = n / 3;
39     if (x == 0) {
40         return pow(3, y);
41     }
42     else if (x == 1) {
43         return 2 * 2 * (long long)pow(3, y - 1);
44 is      }
 45      the else {
 46 is          return  2 * ( Long  Long ) POW ( . 3 , Y);
 47      }
 48  }
 49  
50  // give you a string of length n, m please cut the rope section (m, n are is an integer, n> 1 and m> 1), the length of each rope is referred to as k [0], k [1 ], ..., k [m]. Will k [0] xk [1] x ... xk [m] maximum possible product is how much? For example, when the length of the rope is 8:00, we cut it into lengths of three sections 2,3,3 of the product obtained at this time is the maximum 18.
51  // 
52  // Input Description:
 53  // input a number n, meaning title see surface. (2 <= n-<= 100)
 54 is  // 
55  // 
56 is  // Output Description:
 57  // output answer.
58  // Example 1
59  // input
 60  // . 8
 61 is  // output
 62 is  @ 18 is 
63 is  int main () {
 64      Long  Long n-= 0 ;
 65      CIN >> n-;
 66      COUT << n_max_3 (n-) << endl;
 67      return  0 ;
 68 }

 

Guess you like

Origin www.cnblogs.com/zhiliang9408/p/11520604.html