A number of students sit in a circle facing their teacher in the center. Each student initially has an even number of pieces of candy. When the teacher blows a whistle, each student simultaneously gives half of his or her candy to the neighbor on the right. Any student, who ends up with an odd number of pieces of candy, is given another piece by the teacher. The game ends when all students have the same number of pieces of candy.
Write a program which determines the number of times the teacher blows the whistle and the final number of pieces of candy for each student from the amount of candy each child starts with.
Input
The input may describe more than one game. For each game, the input begins with the number N of students, followed by N (even) candy counts for the children counter-clockwise around the circle. The input ends with a student count of 0. Each input number is on a line by itself.
Output
For each game, output the number of rounds of the game followed by the amount of candy each child ends up with, both on one line.
Sample Input
6
36
2
2
2
2
2
11
22
20
18
16
14
12
10
8
6
4
2
4
2
4
6
8
0
Sample Output
15 14
17 22
4 8
Hint
The game ends in a finite number of steps because:
- The maximum candy count can never increase.
- The minimum candy count can never decrease.
- No one with more than the minimum amount will ever decrease to the minimum.
- If the maximum and minimum candy count are not the same, at least one student with the minimum amount must have their count increase.
题解
题意:
- 初始:每个学生最初都有偶数的糖果。
- 循环:当老师吹口哨时,对于某一个学生,将自己一半的糖果给下一位同学,并获得上一位同学一半的糖果。如此操作后,如果他的糖果数目为奇数,就会再得到一个糖果。
- 结束:游戏结束时,所有的学生都有相同数量的糖果N。输出老师吹哨的次数(循环次数)和N。
思路:
- 将学生的糖果数按顺序存入一个数组 N[500] 。
- 遍历数组,当读到 N[i] 时,计算上一位学生分出一半前的数目(用b表示)与当前学生糖果数目的平均值a,记录下其当前学生的糖果数目 b = N[i],更新 N[i] = (a % 2 + a / 2) * 2(a为奇数则a加一,偶数则不变)。
- 以上是对单个学生的操作。每遍历并更新一次数组N[ ],计数器cnt++(吹口哨的次数)。每次循环前判断N[0]到N[n-1]是否都相等,若相等,则结束外层循环,输出结果。
Code
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
using namespace std;
bool eq(int data[], int n)//判断数组中所有数据是否相等
{
for (int i = 0; i < n; i++)
{
if(data[i] != data[0])
return 0;
}
return 1;
}
int main()
{
int n, a, b, N[500], cnt = 0;
while(cin >> n)
{
cnt = 0;
if(n == 0)
break;
else if(n == 1)
{
int num;
cin >> num;
cout << cnt << ' ' << num << endl;
continue;
}
for(int i = 0; i < n; i++)
cin>>N[i];
while(!eq(N, n))//当不全相等时,进行循环
{
a = (N[n-1] + N[0]) / 2;//第一个学生的上一位为最后一位
b = N[0];
N[0] = (a % 2 + a / 2) * 2;
for(int i = 1;i < n; i++)
{
a = (b + N[i]) / 2;//计算吹口哨前的平均值
b = N[i];//记录吹口哨前的数值
N[i] = (a % 2 + a / 2) * 2;
}
cnt++;
}
cout << cnt << ' ' << N[0] << endl;
}
}