题意大概是两只青蛙在长度为L的坐标上的x点和y点分别每步跳n和m个点,问能不能相遇,如果能相遇,输出最少步数.
思路:用扩展欧几里得算法求不定方程ax+by=c。扩展欧几里得的数学证明好多。。。。
#include <iostream>
using namespace std;
#define LL long long
LL Gcd(LL a, LL b)
{
return b ? Gcd(b, a%b) : a;
}
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 GetAns(LL a, LL b, LL c, LL &ans)// 求最小解
{
LL r = Gcd(a, b), y0;
if (c%r) //无整数解
{
return 0;
}
a /= r, b /= r, c /= r;
ExGcd(a, b, r, ans, y0); // 取得一组解,通过这一组解得到全部的解
// p = p1 + b/Gcd(a, b) * t
// q = q1 - a/Gcd(a, b) * t(其中t为任意整数)
LL t = c * ans / b; //最小值应该为0,如果不能取得0,那对应的t求出来的就是最小值
ans = c * ans - t * b; //求出来的ans如果小于0,证明t应该等于t+1
if (ans < 0)
{
ans += b;
}
return 1;
}
int main()
{
LL x, y, m, n, L;
while (cin >> x >> y >> m >> n >> L)
{
LL a = n - m, b = L, c = x - y;
LL ans;
int flag = GetAns(a, b, c, ans);
if (!flag)
{
cout << "Impossible" << endl;
continue;
}
cout << ans << endl;
}
}