首页 > ACM题库 > HDU-杭电 > hdu 2088 Box of Bricks-模拟[解题报告]C++
2013
12-29

hdu 2088 Box of Bricks-模拟[解题报告]C++

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 consideration, 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?

输入:

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.

输出:

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.

样例输入:

6
5 2 4 1 7 5
0

样例输出:

5

开始对以前题目的总结,嘛,虽然都是水题。

 题目:http://acm.hdu.edu.cn/showproblem.php?pid=2088

把所有砖移成一样高的最少移动块数,把所有高于AVG的砖移成AVG就是答案。

#include <iostream>     
using namespace std;          
int main()
{      
    int a[50],sum,k=0,i,n;
    while(cin>>n,n)
    {
        sum=0;
        for(i=0;i<n;i++)
        {    
            cin>>a[i];
            sum+=a[i];
        }
        sum/=n;
        int ans=0;
        for(i=0;i<n;i++)
            if(a[i]>sum)
                ans+=a[i]-sum;
        cout<<"Set #"<<++k<<endl;
        cout<<"The minimum number of moves is "<<ans<<"."<<endl;
        cout<<endl;
    }
    return 0;
}

 

解题转自:http://www.cnblogs.com/destino74/p/3327793.html


  1. 这道题目虽然简单,但是小编做的很到位,应该会给很多人启发吧!对于面试当中不给开辟额外空间的问题不是绝对的,实际上至少是允许少数变量存在的。之前遇到相似的问题也是恍然大悟,今天看到小编这篇文章相见恨晚。

  2. 如果两个序列的最后字符不匹配(即X [M-1]!= Y [N-1])
    L(X [0 .. M-1],Y [0 .. N-1])= MAX(L(X [0 .. M-2],Y [0 .. N-1]),L(X [0 .. M-1],Y [0 .. N-1])
    这里写错了吧。