Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 99341 | Accepted: 18926 |
Description
我们把这两只青蛙分别叫做青蛙A和青蛙B,并且规定纬度线上东经0度处为原点,由东往西为正方向,单位长度1米,这样我们就得到了一条首尾相接的数轴。设青蛙A的出发点坐标是x,青蛙B的出发点坐标是y。青蛙A一次能跳m米,青蛙B一次能跳n米,两只青蛙跳一次所花费的时间相同。纬度线总长L米。现在要你求出它们跳了几次以后才会碰面。
Input
Output
Sample Input
1 2 3 4 5
Sample Output
4
对扩展欧几里得,首先给出三个定理
定理一:如果d = gcd(a, b),则必能找到正的或负的整数k和l,使d = a*x+ b*y。
定理二:若gcd(a, b) = 1,则方程ax ≡ c (mod b)在[0, b-1]上有唯一解。
定理三:若gcd(a, b) = d,则方程ax ≡ c (mod b)在[0, b/d - 1]上有唯一解。
声明一下——式子ax + by = c 和 ax ≡ c (mod b)是可以相互转化的。
思路:设最少跳t次可以碰面,那么可以得到(x + m * t) - (y + n * t) = k * L。(其中k为整数)
转化该式——k * L + (n - m) * t = x - y
设d = gcd(n-m, L),因为x-y可能不是n-m和L的最大公约数,设time = (x-y) / d。
式子k * L + (n - m) * t = time * d -————> k * L / time + (n - m) * t / time = d
这样就对应了a * x + b * y = c的形式,其中a = L, b = n - m,x = L / time,y = t / time。
利用扩展欧几里得求出x,y,这样就得到t = y * time。
由定理三:可知在[0, b/d-1] 即 [0, L/d-1]上有唯一解,这样的话我们只需要对求出的t 对 L/d取余就可以了。
AC代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#define LL long long
using namespace std;
//求解ax + by = gcd(a, b) = d,可以求出x和y。
//x和y可能是负数或者0 且求出的|x| + |y|最小
void exgcd(LL a, LL b, LL &d, LL &x, LL &y)
{
if(!b)
{
d = a;
x = 1;
y = 0;
}
else
{
exgcd(b, a%b, d, y, x);
y -= x * (a / b);
}
}
int main()
{
LL x, y, m, n, L;
while(scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &L) != EOF)
{
LL k, t, d;
exgcd(L, n-m, d, k, t);
if((x-y) % d)
{
printf("Impossible\n");
continue;
}
L /= d;
printf("%lld\n", ((x - y) / d * t % L + L) % L);
}
return 0;
}