Description
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 <= n <= 50 and 1 <= hi <= 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.
Sample Input
6
5 2 4 1 7 5
0
Sample Output
Set #1
The minimum number of moves is 5.
这道题的基本题意为Bob要建一座等齐的墙,由于各排砖不一定一样高,要求求至少移动多少转可以将墙建成齐的。
基本思路为求各排低于平均砖数的总和或各排高于平均砖数的总和。
源代码如下:
#include<bits/stdc++.h>
using namespace std;
int main()
{ int n,i,m,h,k,p,x=1;
multiset<int>a;
multiset<int>::iterator it;
while(cin>>n&&n!=0)
{ a.clear();
for(h=0,i=0;i<n;++i)
{ cin>>m;
h+=m;
a.insert(m);
}
k=0;
p=h/n;
for(it=a.begin();*it<p;++it)
k+=p-*it;
cout<<"Set #"<<x<<endl<<"The minimum number of moves is "<<k<<"."<<endl<<endl;
++x;
}
}
需要注意的就是:这里面可能有相同的数据,所以应该用multiset型而不能用set型;其次就是输出格式要看仔细,
一不小心输出格式就错了。
Bob面对不同高度的砖墙堆,为了满足姐姐的要求,需要将所有砖墙调整到同一高度。本篇介绍了一种算法,通过计算各砖堆与平均高度的差异,找出最少移动砖块的数量。
2671

被折叠的 条评论
为什么被折叠?



