1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 5 public class Main { 6 private static int m; 7 private static int[] sweetsNum; 8 private static int addNum; //增加的糖果数 9 public static void main(String[] args) throws NumberFormatException, IOException { 10 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 11 m = Integer.parseInt(br.readLine()); 12 13 sweetsNum = new int[m]; 14 String[] str = br.readLine().split(" "); 15 for(int i = 0; i < m; i++){ 16 sweetsNum[i] = Integer.parseInt(str[i]); 17 } 18 19 candy(m,sweetsNum); 20 21 System.out.println(addNum); 22 } 23 24 /** 25 * 分糖果 26 * @param m 学生个数 27 * @param sweetsNum 每个学生的糖果数 28 */ 29 private static void candy(int m, int[] sweetsNum) { 30 while(true){ 31 if(equal(sweetsNum)){ 32 return; 33 }else{ 34 //每个小朋友都把自己的糖果分一半给左手边的孩子 35 int temp = sweetsNum[0]; 36 for(int i = 0; i < sweetsNum.length-1; i++){ 37 sweetsNum[i] = sweetsNum[i+1]/2 + sweetsNum[i]/2; 38 } 39 sweetsNum[sweetsNum.length-1] = temp/2 + sweetsNum[sweetsNum.length-1]/2; 40 41 //老师给奇糖果数的孩子补糖果 42 for(int i = 0; i < sweetsNum.length; i++){ 43 if(sweetsNum[i]%2 != 0){ 44 addNum++; //记录补的糖果数的数目 45 sweetsNum[i]++; 46 } 47 } 48 } 49 } 50 } 51 52 /** 53 * 判断所有学生手中的糖果数是否相等 54 * @param sweetsNum 每个学生的糖果数 55 * @return 相等返回true,否则返回false 56 */ 57 private static boolean equal(int[] sweetsNum) { 58 int n = 0; 59 for(int i = 1; i < sweetsNum.length; i++){ 60 if(sweetsNum[i] == sweetsNum[0]){ 61 n++; 62 } 63 } 64 if(n == sweetsNum.length-1){ 65 return true; 66 } 67 return false; 68 } 69 }
原文:http://www.cnblogs.com/cao-lei/p/6628317.html