历届试题 分糖果
2017-01-29 19:48
246 查看
问题描述
有n个小朋友围坐成一圈。老师给每个小朋友随机发偶数个糖果,然后进行下面的游戏:
每个小朋友都把自己的糖果分一半给左手边的孩子。
一轮分糖后,拥有奇数颗糖的孩子由老师补给1个糖果,从而变成偶数。
反复进行这个游戏,直到所有小朋友的糖果数都相同为止。
你的任务是预测在已知的初始糖果情形下,老师一共需要补发多少个糖果。
输入格式
程序首先读入一个整数N(2
有n个小朋友围坐成一圈。老师给每个小朋友随机发偶数个糖果,然后进行下面的游戏:
每个小朋友都把自己的糖果分一半给左手边的孩子。
一轮分糖后,拥有奇数颗糖的孩子由老师补给1个糖果,从而变成偶数。
反复进行这个游戏,直到所有小朋友的糖果数都相同为止。
你的任务是预测在已知的初始糖果情形下,老师一共需要补发多少个糖果。
输入格式
程序首先读入一个整数N(2
import java.util.Scanner; /* * 这是分糖果类 */ class Candle{ private int N; private int[] candle; private int count; /* * 这是构造方法 */ public Candle() { super(); Scanner in = new Scanner(System.in); N = in.nextInt(); this.count = 0; candle = new int ; for ( int i = 0 ; i < candle.length ; i++){ candle[i] = in.nextInt(); } in.close(); } /* * 分配一轮方法 */ public void Distribute_OneTime(){ int[] tmp = new int[this.N]; for ( int i = 0 ; i <tmp.length ; i++){ tmp[i] = this.candle[i] / 2; } for( int i = 0 ; i < N ; i++){ int j; if ( i == 0){ j = N-1; }else{ j = i-1; } this.candle[i] += tmp[j]; this.candle[i] -= tmp[i]; } } /* * 分配方法 */ public void Distribute(){ while(true){ if(IsSame()){ break; }else{ this.Distribute_OneTime(); this.AddOneCandle(); } } } /* * 奇数糖果加一方法 */ public void AddOneCandle(){ for ( int i = 0 ; i < N ; i++){ if (this.candle[i] % 2 != 0){ this.candle[i]++; this.count++; } } } /* * 判断数组是够全相等 */ public boolean IsSame(){ boolean flag = true; for ( int i = 0 ; i < N - 1 ; i++){ for ( int j = i+1 ; j < N ; j++){ if(this.candle[i] != this.candle[j]){ flag = false; break; } } if (flag == false){ break; }else{ continue; } } return flag; } public void Print_Count(){ System.out.print(count); } } /* * 这是测试类 */ public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Candle test = new Candle(); test.Distribute(); test.Print_Count(); } }
相关文章推荐
- 算法笔记_170:历届试题 分糖果(Java)
- 蓝桥杯 历届试题 分糖果 【模拟】
- 历届试题 分糖果
- 蓝桥网-历届试题 分糖果 简单模拟
- 蓝桥杯-历届试题-分糖果-java
- 蓝桥杯 历届试题 分糖果 (简单模拟)
- 历届试题 分糖果
- 历届试题 分糖果
- 蓝桥杯 历届试题 分糖果
- 蓝桥杯-历届试题 分糖果
- 蓝桥杯 历届试题 分糖果
- 历届试题 分糖果
- 蓝桥杯 - 历届试题 分糖果 C语言实现
- 蓝桥杯 历届试题 分糖果 (模拟)
- 蓝桥杯历届试题 分糖果(简单模拟)
- 问题 1431: [蓝桥杯][历届试题]分糖果
- 蓝桥杯 历届试题 分糖果
- 历届试题 分糖果
- 蓝桥杯--历届试题 分糖果(模拟水题)
- 历届试题 分糖果