HDU 1222 Wolf and Rabbit //gcd+欧几里德算法求解不定方程的应用

本文探讨了一个有趣的数学问题——狼按固定步长绕圈寻找藏于洞中的兔子。通过分析得出,若狼的步长与洞总数互质,则兔子无法存活;反之,则存在安全洞。文章还介绍了使用扩展欧几里德算法验证这一结论的方法。

Wolf and Rabbit

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2749 Accepted Submission(s): 1516
 
Problem Description
There is a hill with 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 in anticlockwise order. The first hole he get into is the one signed with 0. Then he will get into the hole every m holes. For example, m=2 and n=6, the wolf will get into the holes which are signed 0,2,4,0. If the rabbit hides in the hole which signed 1,3 or 5, she will survive. So we call these holes the safe holes.
 
Input
The input starts with a positive integer P which indicates the number of test cases. Then on the following P lines,each line consists 2 positive integer m and n(0<m,n<2147483648).
 
Output

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

思路历程:一开始想用vis数组存储各个洞是否被访问,如果有一个洞被二次访问,则接下来就是个循环过程,如果此时有洞没有被访问过,则YES,反之NO。提交后爆了内存,仔细一看发现m,n可以取到2^31,数组爆了也就可以解释了。接着想是否可以把n转化为快速幂的形式,但感觉太过于复杂,还是去搜了别人的代码:

m,n互质 则”NO”,反之为”YES”。

可是这是为什么呢?解释如下:

题目要求如果所有洞都被狼走过则”NO”,我们设狼进洞的位置为P,总的洞为n,狼进洞间隔为m;则得到 
p = m * x - n * y; 
此时涉及到扩展欧几里德求不定方程的性质 :

扩展欧几里德算法应用 之 求解不定方程 
对于不定整数方程ax+by=c,求解满足其方程的整数解。

这里我只学习了其应用,没有追溯它的原理: 
不定整数方程ax+by=gcd(a,b),一定有整数解x0,y0。
若c mod gcd(a,b)==0,则必有解:  x=x0 * c / gcd(a,b)  y= y0 * c/gcd(a,b)  (即将等式左右同时扩大c/gcd(a,b)倍)
所以  当gcd(a,b)=1 时,任意 c 都有整数解,即任何位置p都能有解,即任何位置狼都能走到。

贴一个欧几里德算法的代码

int gcd(int a,int b)
{
	return a%b==0?b:gcd(b,a%b);
}

附AC代码:
#include<cstdio>
using namespace std;
int gcd(int a,int b)
{
	return a%b==0?b:gcd(b,a%b);
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int n,m;
		scanf("%d%d",&m,&n);
		if(gcd(m,n)==1)
			printf("NO\n");
		else printf("YES\n");	
	}
	return 0;
} 
 
关于欧几里德算法的其他应用参考   点击打开链接



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值