|
| 1 | +package q14_剪绳子; |
| 2 | + |
| 3 | +public class CuttingRope { |
| 4 | + public static void main(String[] args) { |
| 5 | + test("Test1", 1, 0); |
| 6 | + test("Test2", 2, 1); |
| 7 | + test("Test3", 3, 2); |
| 8 | + test("Test4", 4, 4); |
| 9 | + test("Test5", 5, 6); |
| 10 | + test("Test6", 6, 9); |
| 11 | + test("Test7", 7, 12); |
| 12 | + test("Test8", 8, 18); |
| 13 | + test("Test9", 9, 27); |
| 14 | + test("Test10", 10, 36); |
| 15 | + test("Test11", 50, 86093442); |
| 16 | + |
| 17 | + } |
| 18 | + |
| 19 | + private static int maxProductAfterCutting_DP(int length) { |
| 20 | + if (length < 2) |
| 21 | + return 0; |
| 22 | + if (length == 2) |
| 23 | + return 1; |
| 24 | + if (length == 3) |
| 25 | + return 2; |
| 26 | + int[] products = new int[length + 1]; |
| 27 | + //为什么products[3]=3,而不是2,是因为如果长度大于3,3可以不减。 |
| 28 | + products[1] = 1; |
| 29 | + products[2] = 2; |
| 30 | + products[3] = 3; |
| 31 | + int max; |
| 32 | + for (int i = 4; i <= length; i++) { |
| 33 | + max = 0; |
| 34 | + for (int j = 1; j <= i / 2; j++) { |
| 35 | + int product = products[j] * products[i - j]; |
| 36 | + if (max < product) |
| 37 | + max = product; |
| 38 | + products[i] = max; |
| 39 | + } |
| 40 | + } |
| 41 | + max = products[length]; |
| 42 | + return max; |
| 43 | + } |
| 44 | + |
| 45 | + private static int maxProductAfterCutting_GA(int length) { |
| 46 | + if (length < 2) |
| 47 | + return 0; |
| 48 | + if (length == 2) |
| 49 | + return 1; |
| 50 | + if (length == 3) |
| 51 | + return 2; |
| 52 | + int timesOf3 = length / 3; |
| 53 | + if (length - timesOf3 * 3 == 1) |
| 54 | + timesOf3 -= 1; |
| 55 | + int timesOf2 = (length - timesOf3 * 3) / 2; |
| 56 | + return (int) Math.pow(3, timesOf3) * (int) Math.pow(2, timesOf2); |
| 57 | + } |
| 58 | + |
| 59 | + private static void test(String name, int length, int expected) { |
| 60 | + System.out.println(name + ": "); |
| 61 | + System.out.print("Test with DP: "); |
| 62 | + if (maxProductAfterCutting_DP(length) == expected) |
| 63 | + System.out.println("Passed."); |
| 64 | + else |
| 65 | + System.out.println("Failed."); |
| 66 | + System.out.print("Test with DA: "); |
| 67 | + if (maxProductAfterCutting_GA(length) == expected) |
| 68 | + System.out.println("Passed."); |
| 69 | + else |
| 70 | + System.out.println("Failed."); |
| 71 | + System.out.println("================="); |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments