Content

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 #1
6
5 2 4 1 7 5
3
1 1 1
0
Sample Output #1
Set #1
The minimum number of moves is 5.

Set #2
The minimum number of moves is 0.

C++:

/*
6
5 2 4 1 7 5
3
1 1 1
0
*/
#include <iostream> 
#include <math.h>
using namespace std;

int main(){
	int n;
	int index=1;
	
	while(cin>>n){
		if(n==0)break;
		int sum=0,avg;
		int ans=0;
		int arr[n];
		for(int i=0;i<n;i++){
			cin>>arr[i];
			sum+=arr[i];
		}
		avg=sum/n;
		
		for(int i=0;i<n;i++){
			ans+=abs(avg-arr[i]) ;
		}
		cout<<"Set #"<<index<<'\n';
		cout<<"The minimum number of moves is "<<ans/2<<".\n";
		index++;
	}
	
	
	return 0;
}

python:

from sys import stdin
flag=1
for s in stdin:
    
    n=int(s)
    if n==0:break
    arr=list(map(int,stdin.readline().strip('\n').split()))
    
    ans=0
    #print(arr)
    avg=sum(arr)//n
    for i in range(n):
        ans+=abs(avg-arr[i])
    print(f"Set #{flag}")
    print(f"The minimum number of moves is {ans//2}.")
    print()
    flag+=1
arrow
arrow
    創作者介紹
    創作者 趴趴熊日常 的頭像
    趴趴熊日常

    資工趴趴熊的小天地

    趴趴熊日常 發表在 痞客邦 留言(0) 人氣()