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

这是一个关于杭电1034题目的解析,内容涉及模拟法解决小朋友分糖果问题。初始时,每个孩子手中的糖果数为偶数。每轮游戏,孩子们将糖果数减半并传给右侧的小伙伴。若一轮结束有孩子持有奇数糖果,教师会补给一颗。问题求解所有孩子持有相同糖果数所需的轮数,并输出该数字。解决方案是通过直接模拟游戏过程来实现。
摘要由CSDN通过智能技术生成
Problem Description
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

题意: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值