首页 > 专题系列 > Java解POJ > POJ 1477 Box of Bricks [解题报告] Java
2013
11-09

POJ 1477 Box of Bricks [解题报告] Java

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?


输入:

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.

输出:

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.

样例输入:

6
5 2 4 1 7 5
0

样例输出:

Set #1
The minimum number of moves is 5.

解题代码:

//* @author: 82638882@163.com
import java.util.Scanner;
public class Main
{
 public static void main(String[] args)
 {
  Scanner in=new Scanner(System.in);
  int c=0;
  while(true)
  {
	int a=in.nextInt();
	if(a==0)break;
	c++;
	int[] arr=new int[a];
	int total=0;
	for(int i=0;i< a;i++)
	{
		arr[i]=in.nextInt();
		total+=arr[i];
	}
	total/=a;
	int ans=0;
	for(int i=0;i< a;i++)
	{
		if(arr[i]>total)
			ans+=arr[i]-total;
	}
	System.out.println("Set #"+c);
	System.out.println("The minimum number of moves is "+ans+".");
	System.out.println();
   }
 }
}

  1. Thanks for using the time to examine this, I truly feel strongly about it and enjoy finding out far more on this subject matter. If achievable, as you achieve knowledge

  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])
    这里写错了吧。