Problem Description
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”.
先给出代码:
#include<iostream>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m)
{
if(n==-1&&m==-1)
{
break;
}
while(m!=0)
{
int temp=m;
m=n%m;
n=temp;
}
if(n==1)
{
cout<<"YES"<<endl;
}
else
{
cout<<"POOR Haha"<<endl;
}
/*
// bool flag=true;
// bool array[128]={false};
// array[0]=true;
// int temp=0;
// for(int i=0;i<n-1;i++)
// {
// temp=(temp+m)%n;
// if(array[temp]==true)
// {
// flag=false;
// break;
// }
// array[temp]=true;
// }
// if(flag)
// {
// cout<<"YES"<<endl;
// }
// else
// {
// cout<<"POOR Haha"<<endl;
// }
*/
}
return 0;
}
代码的分析:
这道题其实很容易就会想到想依次走,走到原来走过的盒子就会失败,
所以一开始我就是用了一个for循环,之所以是到n-1,是因为一开始已经
确定了一个盒子,所以接下来只要确定之后的n-1个盒子没有重复就可以保证走完,
要是有重复也肯定会在这n-1步中出现,所以循环n-1次,
但是看到了n的范围,我就发现前面我们保存走过盒子的数组array根本无法保存所有的盒子,
所以提交的时候出现运行时错误,
其实这道题真正想说的是利用n和m的最大公因子(辗转相除法求最大公因子),
只有最大公因子为1的时候,我们才能真正的走完所有的盒子,原因很简单,只有当n和m的
最大公因子为1的时候,他们的最小公倍数为n*m,
也是当这个人走过n*m的时候才会回到一开始的地方,
只有这样才能找到n个不同的盒子(找一个盒子需要m步),
否则的话,这个人无法走n*m步就会回到一开始的位置,就无法找到n个盒子,所以就一定会失败。