591 - Box of Bricks

Little Bob likes playing with his box of bricks. He puts the bricks one upon another and builds stacks of different height. ``Look, I've built a wall!'', he tells his older sister Alice. ``Nah, you should make all stacks the same height. Then you would have a real wall.'', she retorts. After a little con- sideration, Bob sees that she is right. So he sets out to rearrange the bricks, one by one, such that all stacks are the same height afterwards. But since Bob is lazy he wants to do this with the minimum number of bricks moved. Can you help?

Input 

The input consists of several data sets. Each set begins with a line containing the number n of stacks Bob has built. The next line contains n numbers, the heights hi of the n stacks. You may assume $1 Ÿ\le n \leŸ 50$ and $1 \leŸ h_i Ÿ\le 100$.

The total number of bricks will be divisible by the number of stacks. Thus, it is always possible to rearrange the bricks such that all stacks have the same height.

The input is terminated by a set starting with n = 0. This set should not be processed.

Output 

For each set, first print the number of the set, as shown in the sample output. Then print the line ``The minimum number of moves is k.'', where k is the minimum number of bricks that have to be moved in order to make all the stacks the same height.

Output a blank line after each set.

3岁的小明喜欢玩他的方块积木,他总是把方块叠在一起形成高度不一的方块堆。然后他说:这是一面墙。 5岁的姊姊小美听到了就跟小明说:真正的墙高度应该要一样才行。小明听了觉得有道理于是决定要搬动一些方块使所有方块堆的高度一样。如下图。由于小明是个懒惰的小孩,他想要搬动最小数目的方块以达成这个目的,你能帮助他吗?
Input

输入包含好几组资料,每组资料有2行,第一行有一个数字n,代表有几堆方块。第二行有n个数字分别代表这n堆方块的高度hi。你可以假设1<=n<=50 1<=hi<=100
方块的总数一定可以整除堆数n,也就是说一定可以使所有的方块堆同样高度。
如果输入的n=0,代表输入结束。

Output

对每一组输入资料,首先输出一行这是第几组测试资料,下一行为"The minimum number of moves is k." k在这里就是需搬动方块最小的数目以使所有的方块堆同一高度每组测试资料后亦请空一行。请参考Sample Output.

Sample Input 

6
5 2 4 1 7 5
0

Sample Output 

Set #1
The minimum number of moves is 5.

解题思路:先求出平均数再分别计算各数与平均数的差相加

注意:在两个测试结果中间要空一行

还有对hi数组在第二组数据中的重新定义

#include<stdio.h>
int main()
{int t=1,n,i,sum,min;
while(scanf("%d",&n)!=EOF){int hi[50]={0};
                           if(n==0)break;
                           for(sum=i=0;i<n;i++){
                                                scanf("%d",&hi[i]);
                                                sum+=hi[i];
                                                }
                           sum/=n;
                           for(min=i=0;i<n;i++)
                           if(hi[i]>sum)
                           min+=(hi[i]-sum);
                           else min+=(sum-hi[i]);
                           printf("Set #%d\n",t);
                           t++;
                           printf("The minimum number of moves is %d.\n\n",min/2);
                           }
return 0;
}

posted on 2013-02-05 09:52  喂喂还债啦  阅读(1730)  评论(0编辑  收藏  举报