Candy Sharing Game——hdu1034

题目

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.

机翻。。:

许多学生坐成一个圆圈,面对中间的老师。每个学生最初都有偶数块糖果。当老师吹口哨时,每个学生同时把自己一半的糖果给右边的邻居。任何一个最后得到奇数块糖果的学生,老师都会给另一块。当所有学生都有相同数量的糖果时游戏结束。编写一个程序,根据每个孩子开始吃的糖果量,确定老师吹口哨的次数和每个学生最后吃的糖果数量。

要点

  • simultaneously 同时。

    理解此题的关键,开这篇博文的目的只是想记录这个问题

    糖果是被同时移送给右边的同学,而不是一个一个的传递

  • 每次吹口哨之前都要确保每个同学手上都有偶数个糖果。

别人家的代码

/**************************************
***************************************
*        Author:Tree                 *
*From  :http://blog.csdn.net/lttree  *
* Title : Candy Sharing Game          *
*Source: hdu 1034                     *
* Hint  : 模拟题                      *
***************************************
**************************************/
#include <iostream>
using namespace std;
int arr[100001];
bool judge(int n)
{
    int i;
    for(i=2;i<=n;++i)
        if( arr[1]!=arr[i] )
            return false;
    return true;
}
int main()
{
    int i,test,step;
    while( cin>>test && test )
    {
        for(i=1;i<=test;++i)
            cin>>arr[i];
        step=0;
        while( !judge(test) )
        {
            arr[0]=arr[test];
            for(i=test;i>0;--i)
            {
                arr[i]=(arr[i-1]/2+arr[i]/2);
                // 位运算判断奇偶,肯定比%2快
                if( arr[i]&1 )  ++arr[i];
            }
            ++step;
        }
        cout<<step<<" "<<arr[1]<<endl;
    }
    return 0;
}

p.s

  • 做题先审题5遍,最好能够手动模拟下整个过程,而不是刚打开就开码

  • 或许自己得遵循这个规则了。。

    1、超过15分钟无思路,放弃。

    2、超过30分钟无编程实现,放弃。

    3、超过20分钟无法成功修改BUG,放弃。

    4、多看题解,多总结方法,题海战术,不要自己想算法,白费脑子!!!

  • 关于位运算判断奇偶

    自己今后也试着尝试这种办法了,原理很简单

    • & 与运算符 都为1结果才为1
    • 偶数二进制位最低位为0,奇数为1
posted @ 2019-01-21 20:36  StarSpark0  阅读(200)  评论(0编辑  收藏  举报