您的位置:首页 > 编程语言 > C语言/C++

贪心算法之Packets

2015-08-09 14:40 429 查看
Packets
Description
A factory producesproducts packed in square packets of the same height h and of the sizes 1*1,2*2, 3*3, 4*4, 5*5, 6*6. These products are always delivered to customers inthe square parcels of the same height h as the products have and of the
size6*6. Because of the expenses it is the interest of the factory as well as ofthe customer to minimize the number of parcels necessary to deliver the orderedproducts from the factory to the customer. A good program solving the problemof finding the minimal
number of parcels necessary to deliver the givenproducts according to an order would save a lot of money. You are asked to makesuch a program.
Input
The input fileconsists of several lines specifying orders. Each line specifies one order.Orders are described by six integers separated by one space representingsuccessively the number of packets of individual size from the smallest size1*1
to the biggest size 6*6. The end of the input file is indicated by the linecontaining six zeros.
Output
The output filecontains one line for each line in the input file. This line contains theminimal number of parcels into which the order from the corresponding line ofthe input file can be packed. There is no line in the output file correspondingto
the last ``null'' line of the input file.
Sample Input
0 0 4 0 0 1
7 5 1 0 0 0
0 0 0 0 0 0
Sample Output
2
1
题目意思解读:就是有6中不同面积的盒子,现在分别输入着六种面积的盒子的数目,求一共需要多少个6*6的盒子才能完全装下他们。

解题思路:典型的贪心算法。

面积为6*6,5*5,4*4的盒子必须得单独装一个盒子。

面积为3*3的箱子至多四个位于同一个箱子

面积为2*2的箱子可以组装在面积为4*4和3*3剩余的箱子中。

剩下的装面积为1*1的。

显然,对于4*4的箱子来说,可以装5个2*2的箱子

对于3*3的箱子来说,如果只有一个,可以装5个2*2,如果有两个,可以装3个,如果有三个,可以装1个,如果有四个,只能装0个。

 根据上述思想,得到的代码如下:

 

 

 

#include<iostream>

using namespace std;

 

int main()

{

         intvalue[7];//value[i]表示i*i箱子的数目

         intkey[4]={0,5,3,1};

         while(1)

         {

                   intans=0;

                   for(inti=1;i<7;i++)

                   {

                            cin>>value[i];

                            ans+=value[i];

                   }

                   if(ans==0)

                   {

                            break;

                   }

                   intsum=0;

                   sum=value[6]+value[5]+value[4]+(value[3]+3)/4;

                   inta2=value[4]*5+key[value[3]%4];

                   if(value[2]>a2)

                            sum+=(value[2]-a2+8)/9;

                   inta1=sum*36-value[6]*36-value[5]*25-value[4]*16-value[3]*9-value[2]*4;//用剩余面积计算比较方便

                   if(value[1]>a1)

                            sum+=(value[1]-a1+35)/36;

                   cout<<sum<<endl;

         }

         return0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 贪心算法