SRM286Div2,250

この記事は約3分で読めます。

A careless worker planted several poles in a row to build a fence. They all should be the same height, but they were cut at different sizes. The owner wants them not only all at the same height, but also as tall as possible.

Our solution will be to cut the tops of taller poles and “glue” those tops on top of the shorter ones. To do this, we will first sort the poles from tallest to shortest, and proceed as follows:

  • Cut the tip of the tallest pole, leaving its height equal to the average height of the poles (so we do not cut it anymore).
  • “glue” this piece on top of the shortest pole.
  • Re-sort the poles, and continue from the first step until all poles are the same height.

Write a class CuttingPoles with a method countCuts that takes a int[] of pole heights and returns the number of cuts needed to make them all the same height using the algorithm described.

不注意な労働者

 

[java]

import java.util.Arrays;

public class CuttingPoles {

public int countCuts(int[] poles) {
int count=0;
Arrays.sort(poles);
System.out.println("first:"+Arrays.toString(poles));

while (check(poles) == false) {
int ave = average(poles);
poles[0] += poles[poles.length – 1] – ave;
poles[poles.length – 1] = ave;
Arrays.sort(poles);
count++;
}

System.out.println(Arrays.toString(poles));

return count;
}

public boolean check(int[] poles) {
boolean ok = true;
for (int i = 0; i < poles.length – 1; i++) {
ok &= (poles[i] == poles[i + 1]);
}
return ok;
}

public int average(int[] poles) {
int ave = 0;
for (int i = 0; i < poles.length; i++) {
ave += poles[i];
}
return ave / poles.length;
}

}

[/java]

コメント

タイトルとURLをコピーしました