贪心算法已经学了很久了,贪心的思想也已经差不多掌握了,做了一些贪心的题,发现这些题的模板基本差不了太多,struct,cmp,bool,sort基本是离不开这些东西,写起来也比较容易,思路比较清晰。不过在提交时很容易超时,所以在写程序时最好用scanf.printf,虽然写起来比cin和cout麻烦,但运行起来要快的多,还可以使用ios::sync_with_stdio(false);使程序耗时减短。 下面上一道我认为比较好的题目。 A factory produces products 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 in the square parcels of the same height h as the products have and of the size 6*6. Because of the expenses it is the interest of the factory as well as of the customer to minimize the number of parcels necessary to deliver the ordered products from the factory to the customer. A good program solving the problem of finding the minimal number of parcels necessary to deliver the given products according to an order would save a lot of money. You are asked to make such a program. Input The input file consists of several lines specifying orders. Each line specifies one order. Orders are described by six integers separated by one space representing successively the number of packets of individual size from the smallest size 1*1 to the biggest size 6*6. The end of the input file is indicated by the line containing six zeros. Output The output file contains one line for each line in the input file. This line contains the minimal number of parcels into which the order from the corresponding line of the input file can be packed. There is no line in the output file corresponding to 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,5*5以及4*4尺寸的物品每个物品需要占有一个箱子,对于3*3的物品一个箱子可以放4个,2*2的物品箱子可以放9个,1*1的可以放36个。采用面积统计1*1箱子的空位,采用向上去整的方法统计箱子。 程序 #include<iostream> #include<cstdio> #include<cstring> int num[4]={0,5,3,1}; int box[7]; int main() while(1){ int tmp=0; for(int i=1;i<=6;i++){ scanf("%d",&box[i]); tmp+=box[i]; } if(tmp==0) break; int ans=box[6]+box[5]+box[4]+(box[3]+3)/4; //a6,a5,a4,每个物品占有一个箱子(a3 + 3 ) / 4 代表a3的物品需要占 int a2=box[4]*5+num[box[3]%4]; //统计所有的大物品放进箱子中后a2物品的空位子有多少 if(box[2]>a2) ans+=(box[2]-a2+8)/9; int a1=ans*36-box[6]*36-box[5]*25-box[4]*16-box[3]*9-box[2]*4; if(box[1]>a1) //求a1的空位子,只需要统计剩余的面积即可 ans+=(box[1]-a1+35)/36; printf("%d\n",ans); } return 0; }