The Children’s Day has passed for some days .Has you remembered something happened at your childhood? I remembered I often played a game called hide handkerchief with my friends. Now I introduce the game to you. Suppose there are N people played the game ,who sit on the ground forming a circle ,everyone owns a box behind them .Also there is a beautiful handkerchief hid in a box which is one of the boxes . Then Haha(a friend of mine) is called to find the handkerchief. But he has a strange habit. Each time he will search the next box which is separated by M-1 boxes from the current box. For example, there are three boxes named A,B,C, and now Haha is at place of A. now he decide the M if equal to 2, so he will search A first, then he will search the C box, for C is separated by 2-1 = 1 box B from the current box A . Then he will search the box B ,then he will search the box A. So after three times he establishes that he can find the beautiful handkerchief. Now I will give you N and M, can you tell me that Haha is able to find the handkerchief or not. If he can, you should tell me "YES", else tell me "POOR Haha".
Input
There will be several test cases; each case input contains two integers N and M, which satisfy the relationship: 1<=M<=100000000 and 3<=N<=100000000. When N=-1 and M=-1 means the end of input case, and you should not process the data.
Output
For each input case, you should only the result that Haha can find the handkerchief or not.
Sample Input
3 2 -1 -1
Sample Output
YES
按照题目的套路直接写代码,如下:
代码1:
int *vis=new int[n];
memset(vis,0,sizeof vis);
int cnt;
cnt=m;
int i=0;
while(vis[i]==0)
{
vis[i]=1;
i=(i+cnt)%n;
}
bool flag=true;
for(int j=0;j<n;j++)
{
if(vis[j]==0)
{
flag=false;
break;
}
}
if(flag)
cout<<"YES"<<endl;
else
cout<<"POOR Haha"<<endl;
delete[]vis;
方法二:
#include<iostream>
#include<cstdio>
using namespace std;
int m,n;
int main()
{
while(scanf("%d %d",&n,&m))
{
if(m==-1&&n==-1)
{
break;
}
int cnt=1;
int i=0;
i=(i+m)%n;
while(i!=0&&cnt<=n)
{
cnt++;
i=(i+m)%n;
}
if(cnt==n)
cout<<"YES"<<endl;
else
cout<<"POOR Haha"<<endl;
}
return 0;
}
上面的两段代码用来解决如上问题,都是切实可行的,但是,当数据量很大时,O(n)的复杂度貌似都显得有点太慢了,所以呢,我们要透过现象看本质:
这个题:是一个数学题!!!
怎么理解呢?
如果我们从开始一共走了K步,那么可以得到现在所处的位置是(x+k*M)%N。可以知道如果访问到某个节点的时候,这个节点在前面已经出现过了,且这N个节点没有全部访问完的时候结果是不可能访问完这N个节点。如果出现节点重复,此时恰好走了N步,那么就输出yes。以上的想法可以简单的画图理解。
由上述分析可知,如果(x+K*M)%N=x(表示出现重复节点),且K=N时结果是yes,所以化简这个式子有:(K*M)%N=0,那么要找到这个最小的K满足这个式子自然会想到最小公倍数。再进一步想如果N*M是M和N的最小公倍数,那么M和N的最大公约数必然是1。也就有了下面的程序。
#include <iostream>
#include<cstdio>
using namespace std;
int gcb(int n,int m){
if(m==0)
return n;
else
return gcb(m,n%m);
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m),n!=-1||m!=-1)
{
if(gcb(n,m)==1)
cout<<"YES"<<endl;
else
cout<<"POOR Haha"<<endl;
}
return 0;
}