装箱问题
(来源于牛客网)一个工厂制造的产品形状都是长方体,它们的高度都是h,长和宽都相等,一共有六个型号,他们的长宽分别为1×1、2×2、3×3、4×4、5×5、6×6。这些产品通常使用一个 6×6×h 的长方体包裹包装然后邮寄给客户。因为邮费很贵,所以工厂要想方设法的减小每个订单运送时的包裹数量。他们很需要有一个好的程序帮他们解决这个问题从而节省费用。现在这个程序由你来设计。
输入描述:
输入包含多组数据。
每组数据一行,包含六个自然数,分别表示1×1至6×6这六种产品的数量。
输出描述:
对应每组输入,输出最小的包裹数。
示例1
输入
0 0 4 0 0 1
7 5 1 0 0 0
输出
2
1
思路
6*6必须用一个箱子, 5*5的必须用一个,4*4需要一个,剩余位置可以放5个2*2, 3*3 分情况,如3*3箱子数目是4的整数倍,那么/4得到需要的箱子。若是4n+1则,空余位置可以放可以放5个2*2和7个1*1的箱子,若是4n+2可以放3个2*2和6个1*1的箱子, 若是4n+3可以放1个2*2和5个1*1的箱子。优先放置2*2箱子,最后放置1*1 ,如果没有了空余位置在考虑使用新的箱子装。
代码中常数最好用const 变量代替以免混淆。
代码
#include<iostream>
using namespace std;
int main()
{
int b1, b2, b3, b4, b5, b6;
while(cin>>b1>>b2>>b3>>b4>>b5>>b6)
{
//b3
const int bin3NumInOneBox = 4;
int boxSum = 0, box3InBin3Box = -1, bin3BoxSum = 0;
bin3BoxSum = b3 / bin3NumInOneBox;
if (b3 % bin3NumInOneBox != 0)
{
++bin3BoxSum;
box3InBin3Box = b3 % bin3NumInOneBox;
}
int box2InBin3Box = 0, box1InBin3Box = 0;
if(box3InBin3Box != 0)
{
if(1 == box3InBin3Box) box2InBin3Box = 5, box1InBin3Box = 7;
else if (2 == box3InBin3Box) box2InBin3Box = 3, box1InBin3Box = 6;
else if (3 == box3InBin3Box) box2InBin3Box = 1, box1InBin3Box = 5;
}
// b4 b5 b6
int bin4BoxSum = b4, bin5BoxSum = b5, bin6BoxSum = b6;
int box1InBin5Box = 11 * bin5BoxSum,
box2InBin4Box = 5 * bin4BoxSum;
//b2
const int bin2TranBin1Factor = 4, area = 36;
int bin2BoxSum = 0, box1frombox2leftInAllBin = 0;
int box2leftStore = b2 - (box2InBin3Box + box2InBin4Box);
if(box2leftStore > 0)
{
const int bin4NumInOneBox = 9;
bin2BoxSum = box2leftStore / bin4NumInOneBox;
if (0 !=box2leftStore % bin4NumInOneBox)
{
++bin2BoxSum;
int b2left = box2leftStore % bin4NumInOneBox;
box1frombox2leftInAllBin = area - b2left * bin2TranBin1Factor;
}
}
else if (box2leftStore < 0)
{
box1frombox2leftInAllBin = -box2leftStore * bin2TranBin1Factor;
}
//b1
int b1left = box1InBin5Box + box1InBin3Box + box1frombox2leftInAllBin;
int box1leftStore = b1 - b1left, bin1BoxSum = 0;
if(box1leftStore > 0)
{
bin1BoxSum = box1leftStore / area;
if(0 != box1leftStore % area)
{
++bin1BoxSum;
}
}
boxSum = bin1BoxSum + bin2BoxSum + bin3BoxSum + bin4BoxSum + bin5BoxSum + bin6BoxSum;
cout<<boxSum<<endl;
}
}