http://acm.pku.edu.cn/JudgeOnline/problem?id=3372
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3758 | Accepted: 1938 |
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
Source
题目大意:有n个同学坐成一个圆,一老师发糖果,依次发给第1、2、4、7...个同学,问是否每个同学都能得到至少一个糖。
分析:写个朴素的程序,输出1~100的情况后不难发现,只有当n=2^k(k为整数)时,输出YES。
下面转载一个证明:转自http://hi.baidu.com/5l2_/blog/item/6ffa241041f3b007213f2e20.html
要证:
仅当N=2^K(K为整数)时,才能至少每人一糖。
证明:
设第K次到分到第a[K]位小朋友.
a[0]=0,a[1]=1,a[2]=3,a[3]=6……
a[k]=K*(K+1)/2 %N
易知a[k+2*N]=a[k],我们只要考察k取 0—2N-1这2N个数如果构成了N的完全剩余系那每个小朋友至少可得一颗糖,否则有人永远得不到糖。
2N个数有点多,我们通过证明a[N-1-k]=a[N+k],可以把考察范围限定在k取[0,N-1]这N个数。
下证 a[N-1-k]=a[N+k]
a[N-1-K]=(N-K-1)*(N-K)/2 %N
=(N-1-2*K)*N/2 % N +(K+1)*K/2%N
= (N-1)*N/2 % N +(K+1)*K/2%N
= (N+K*N+ (N-1)*N/2 )% N +(K+1)*K/2%N
=(N+1+2*K)*N/2 % N +(K+1)*K/2%N
=(N+K+1)*(N+K) /2 % N
=a[N+K]
下面考察a[0]…a[N-1],如果存在 a[i]=a[j] (i!=j)那么就无法构成N 的完全剩余系,反之存在。
下证仅当N=2^t (t为非负整数) a[0]…a[N-1]两两不等。
1.N为奇数时 a[N-k-1]=(N-1)*N/2 % N +(K+1)*K/2%N=a[k]+ (N-1)*N/2 % N=a[k]
故存在 a[i]=a[j] (i!=j)
2.N=S*2^l (S>1为奇数,l>0)时
a[i]=a[j] (i!=j)等价(j-i)(i+j+1)/2 %N=0.
设 2^t=<S<2^(t+1),M为l和t+1的较大者
令 j-i=S,j+i+1=2^M 解得 j=(S+2^M-1)/2 ,i=(2^M-S-1)/2
0<(S+2^M-1)/2<(S+2*S)/2<2*S<=N
0=(1-1)/2=<(2^M-S-1)/2<(2*S-S-1)/2<2*S<=N
故存在 a[i]=a[j] (i!=j)
3.N=2^l(l>=0)时
假设存在a[i]=a[j] (i!=j)
即(j-i)(i+j+1)/2=K*N. (i!=j)
(j-i)和(i+j+1)不同奇偶,则(j-i)=X*N或(i+j+1)=X*N (X>=1)
0<j-i<=N-1,0<j+i+1<=N-1+N-2+1=2N-2 故只能 i+j+1=N
j-i为奇数 故 (j-i)*N/2 %N!=0
即不存在a[i]=a[j] (i!=j)
由此,得证仅N=2^t (t为非负整数) 时a[0]…a[N-1]两两不等。
证毕!
codes: