原题:
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.
题意:
一圈孩子面对中心老师围坐,老师每吹一次哨所有孩子就把自己一半的糖同时给自己右边,每给完一轮后如果有任何一个孩子手中的糖是单数,老师就会再给他一块糖让他的糖成为双数,求最后所有孩子手中糖数相等的时候的游戏一共进行了多少轮,输出轮数和每个人的糖数。
题解:
1.一个函数来判断是否所有的人糖数相同
2.一个函数来给每一轮结束之后糖数为单数的孩子加糖
3.一个函数来进行给糖,同时给右侧,因为用数组储存,所以先记录最后一个的糖数,然后依次加上前一个的一半,完成一轮
4.依次调用3->2->1完成模拟
5.输出轮数和糖数
(这题解简直不忍直视,主要是真的没用什么算法啊,就是模拟一下就完成了)
代码:AC
#include<iostream>
using namespace std;
int A[10000];
int sum;
int judge(int n)
{
int i;
for(i=0;i<n;i++)
{
if(A[0]!=A[i])
break;
}
if(i==n)
return 1;
else
return 0;
}
void add(int n)
{
int i;
for(i=0;i<n;i++)
{
if(A[i]%2==1)
{
A[i]++;
sum++;
}
}
}
void cycle(int n)
{
int i;
int half=A[n-1]/2;
A[n-1]/=2;
for(i=n-1;i>0;i--)
{
A[i]+=A[i-1]/2;
A[i-1]/=2;
}
A[0]+=half;
}
int main()
{
int n;
while(cin>>n)
{
if(n==0)
break;
else
{
int i;
for(i=0;i<n;i++)
{
cin>>A[i];
}
sum=0;
int max=0;
while(!judge(n))
{
cycle(n);
max++;
add(n);
}
cout<<max<<" "<<A[0]<<endl;
}
}
return 0;
}