您的位置:首页 > 其它

杭电1034(模拟法) 之 Candy Sharing Game

2017-04-26 18:18 323 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

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

[align=left]Sample Output[/align]

15 14
17 22
4 8

题意:n个小朋友围成一圈,刚开始时,每个小朋友手里的糖都是偶数,每个小朋友把手里的糖的一半给右边的小朋友,算完成一轮,一轮结束后,如果哪个小朋友手里的糖变成了奇数,那么老师给他一颗,问:重复多少轮之后,所有的小朋友手里的糖数量一样,并打印这个数字

思路:直接模拟即可

AC代码如下:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=1000;

int a[maxn];

int check(int *a,int n)
{
int flag=0;
int coun=0;
for(int i=1;i<n;i++)
{
if(a[i]==a[0]) coun++;
}
if(coun==n-1) flag=1;
return flag;
}

int main()
{
int n;
while(cin>>n && n)
{
int times=0;
for(int i=0;i<n;i++) cin>>a[i];
if(check(a,n))
{
cout<<0<<" "<<a[0]<<endl;
continue;
}
while(!check(a,n))
{
for(int i=0;i<n;i++)
a[i]/=2;
int kn=a[n-1];
for(int i=n-1;i>=1;i--)
{
a[i]+=a[i-1];
}
a[0]+=kn;
for(int i=0;i<n;i++)
if(a[i]%2==1) a[i]++;
times++;
}
cout<<times<<" "<<a[0]<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: