您的位置:首页 > 其它

poj3372-Candy Distribution

2016-07-14 14:36 288 查看
Description

N children standing in circle who are numbered 1 through N clockwise are waiting their candies. Their teacher distributes the candies by in the following way:

First the teacher gives child No.1 and No.2 a candy each. Then he walks clockwise along the circle, skipping one child (child No.3) and giving the next one (child No.4) a candy. And then he goes on his walk, skipping two children (child No.5 and No.6) and
giving the next one (child No.7) a candy. And so on.

Now you have to tell the teacher whether all the children will get at least one candy?

Input

The input consists of several data sets, each containing a positive integer
N (2 ≤ N ≤ 1,000,000,000).

Output

For each data set the output should be either "YES" or "NO".

Sample Input
2
3
4

Sample Output
YES
NO
YES


代码实现:

#include<iostream>

#include<cstdio>

using namespace std;

int main()

{

    int n;

    while(cin>>n)

    {

        printf("%s",n&(n-1)?"NO":"YES");

        cout<<endl;

    }

    return 0;

}

1.求解的过程中便能发现,手推这道题目的规律非常难推,也尝试过猜测,but WA,既然不好推,程序是干嘛的呢,不就是解决实际问题的,写一段程序来跑一下,代码如下,善于应用取余

#include<iostream>

#include<cstring>

using namespace std;

int main()

{

    int n,a[1000],i,s,sum;//确保输入的n要比数组的数据范围小

    while(cin>>n)

    {

        memset(a,0,sizeof(a));

        a[1]=a[2]=1;

        s=2;

        for(i=1;i<1000000;i++)//这个地方要注意,有的n需要很多次之后才能所有的孩子都拿到糖果,所以i的范围尽量大一点

        {

            s=s+i+1;

            if(s%n==0)

            {

                a
=1;

            }

            else

            {

                a[s%n]=1;

            }

        }

        for(i=1;i<=n;i++)

        {

            cout<<a[i]<<" ";

        }

        cout<<endl;

    }

    return 0;

}

2.推理发现,所有2的倍数都输出YES

3.解释为什么n&(n-1)==0,n便为2的倍数,设n为2的x方

如果n为2的倍数,n除了第x位为1,其他位都为0,而n-1第x位一定为0,所以与的结果为0

其他的数我觉得至少最高非0位相同,这样结果不为0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: