题目:
老王开杂货铺想送N块冬瓜糖砖给客户,每块冬瓜糖砖长宽高都是10厘米,老王希望将这N块冬瓜糖砖包装成一大包(x*y*z的长方体),以便运送。但为了响应环保,希望使用的包装纸越少越好。编写一个程序,输入N,输出最少的包装纸面积。
输入:9
输出:3000
我的想法:
我的想法是以底层个数来分类讨论,分别观察各类情况:
请看表格:
糖块个数 | 底层数 | 面数 | 底层数 | 面数 | 底层数 | 面数 | 底层数 | 面数 | |||
12 | 4 | 32 | 6 | 32 | |||||||
16 | 4 | 40 | 8 | 40 | |||||||
24 | 4 | 56 | 6 | 52 | 8 | 52 | 12 | 52 | |||
32 | 4 | 72 | 8 | 64 | 16 | 64 |
可以很明显的从图表中看出,当糖块为偶数个时,以一半为底数面积最小.
下面用程序来实现:
import java.util.Scanner;
public class Test{
public static void main(String[] a){
final int AREA = 100; //设置一块面积
Scanner scanner = new Scanner(System.in);
boolean flag = true;
int num = 0;
int res = 0;
while(flag){ //个数输入
try{
num = scanner.nextInt();
flag = false;
}catch(Exception e){
System.out.println("input error");
}
}
if(num % 2 == 0){ //为偶数个
if(num == 1){
res = 6;
}else if(num == 2){
res = 10;
}else if(num == 3){
res = 14;
}else if(num == 4){
res = 16;
}else if(num == 12){ //12为特殊个数
res = 3*8+2*4;
}else{
int two = num/2; //有两个面的块数
res = 3*8+2*two+1*(num-two-8);
}
}else{
int num1 = num-1;
flag = true;
while(flag){
if(num % num1 == 0){
int x = num/num1;
int three = 2*(num1-2) + 2*(x-2); //有三个面的块数
res = 4*4 + 3*three + 1*(num-three-4*4);
flag = false;
}else{
res = 5*2+(num-2)*4;
flag = false;
}
num1 = num1 - 1; //如果不是因子就减去1
}
}
res = res*AREA;
System.out.println("糖块个数为:"+num+",其最小包装面积:"+res);
}
}