G - Wolf and Rabbit

题目描述:

         There is a hillwith n holes around. The holes are signed from 0 to n-1.
   

                                                                                               

                                               

A rabbit must hide in one of the holes. A wolf searches the rabbit inanticlockwise order. The first hole he get into is the one signed with 0. Thenhe will get into the hole every m holes. For example, m=2 and n=6, the wolfwill get into the holes which are signed 0,2,4,0. If the rabbit hides in thehole which signed 1,3 or 5, she will survive. So we call these holes the safeholes.

输入:

       The input starts with a positive integerP which indicates the number of test cases. Then on the following P lines,eachline consists 2 positive integer m and n(0<m,n<2147483648).

输出:

         For each input m n, if safe holes exist, you should output"YES", else output "NO" in a single line.

样例输入:

 2

1 2

2 2

样例输出:

         NO

YES

解题思路:

    洞的总数为n,编号依次为0,1,2,···,n-1。狼从第0号洞开始,每次往前查看m个洞,他会查看编号为0,m%n,2m%n,3m%n,···,0的洞。通过一些特殊数据的测试,我发现当m与n互素时,狼会遍历每一个洞,从而兔子没有安全的地方,如果m与n的最大公约数大于1,狼不会遍历每一个洞,那么兔子就有安全的洞可以躲藏。

    其实,洞的编号是数字n所有可能的余数,那么可以将第i(i=0,1,2,…,n-1) 个洞的坐标(也就是编号)表示为n*s+i(s为任意非负整数),也就是说一个洞对于一系列的坐标,这些坐标对n取余数是相同的,都是i。狼查看的洞的坐标也就是0,m,2m,3m,…

    可以发现,当狼查看的坐标为m,n的最小公倍数时,狼就回到了第一个洞(坐标对n的模为0),如果最小公倍数为mq,则狼就查看了q个不同的洞,如果最小公倍数为mn,那么狼就遍历了所有的洞。根据最小公倍数的公式 l.c.m(m,n)=mn/g.c.d(m,n)

最大公因数为1,则最小公倍数为mn,狼就会遍历所有的洞,兔子没有安全的藏身之处;否则兔子就会有安全的地方。

代码:

#include<stdio.h>

int gcd(int a,int b)

{

return b?gcd(b,a%b):a;

}

int main()

{

int p;

scanf("%d",&p);

while(p--)

{

int a,b;

scanf("%d %d",&a,&b);

int m;

m=gcd(a,b);

if(m==1) printf("NO\n");

else printf("YES\n");

}

return 0;

}

猜你喜欢

转载自blog.csdn.net/laisuwen_123/article/details/81122409
今日推荐