poj 1061 青蛙的约会

http://poj.org/problem?id=1061

这是一道扩展GCD的题,说要学习说了好久,总算学会了,得感谢旭娃神牛啊,我一开始不懂为什么要用s*c及其s+b直到s>0,那我就一一解释:1、s*c是因为我们把方程转化为a‘*x+b’*y=1计算实际方程是a*x+by=c;2、s求得只是其中一个解,而s的解无数,s=s0+b*t(t代表正整数);故我们只要加b直到s>0即可,特别注意上诉b,c都是除以gcd(a,b)后的b,c,有不理解的请看:

http://www.cnblogs.com/yuelingzhi/archive/2011/08/13/2137582.html

代码:

#include <stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<math.h>
__int64 gcd(__int64 a,__int64 b)
{
return b?gcd(b,a%b):a;
}
void exgcd(__int64 a,__int64 b,__int64 &x,__int64 &y)
{
if(b==0)
{
x
=1;y=0;
return ;
}
else
{
exgcd(b,a
%b,x,y);
int t=x;
x
=y;
y
=t-(a/b)*y;
}
return ;
}
int main()
{
__int64 x,y,m,n,l;
__int64 a,b,c,s,t,d;
while(scanf("%I64d%I64d%I64d%I64d%I64d",&x,&y,&m,&n,&l)!=EOF)
{
a
=n-m;b=l;c=x-y;d=gcd(a,b);
if(n==m||c%d)
puts(
"Impossible");
else
{
a
/=d;b/=d;c/=d;
exgcd(a,b,s,t);
s
*=c;s%=b;
while(s<0)
s
+=b;
printf(
"%I64d\n",s);
}
}
return 0;
}

  


原文地址:https://www.cnblogs.com/yuelingzhi/p/2138389.html