标签:数学
青蛙的约会
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 91753 | Accepted: 16849 |
Description
Input
Output
Sample Input
1 2 3 4 5
Sample Output
4
分析:设两只青蛙跳S次之后碰面且A比B跳得快,则(x + S * m) - (y + S * n) = k * L(k = 0, 1, 2……)。
移项合并后的(n - m) * S + k * L = (x - y).令a = n - m, b = L, c = x - y,即a * S + b * L = c(1)
若式(1)有整数解,则两只青蛙能相遇,否则不能。所以问题就转化为了求方程的整数解。
首先计算出d = gcd(a, b),如果d不能整除c,则方程无整数解。否则,在方程两边同时除以d,得到a‘ * S + b‘ * L = c‘,此时gcd(a‘, b‘) = 1.
然后利用扩展欧几里得算法求出a‘ * S + b‘ * L = 1‘的一组整数解x0, y0,则(c‘ * x0, c‘ * y0)是a‘ * S + b‘ * L = c‘的一组整数解,a‘ * S + b‘ * L = c‘的所有解为(x = c‘ * x0 + b‘ * k, y = c‘ * y0 - a‘ * k),同时也是a * S + b * L = c的所有解。
写法一:
#include <cstdio> #include <cmath> typedef long long LL; LL X, Y, M, N, L; LL gcd(LL a, LL b) { while(b) { LL r = a % b; a = b; b = r; } return a; } void extend_gcd(LL a, LL b, LL &x, LL &y) { if(b == 0) { x = 1; y = 0; return ; } else { extend_gcd(b, a % b, x, y); LL tmp = x; x = y; y = tmp - a / b * y; } } int main() { LL x, y, d; while(~scanf("%I64d%I64d%I64d%I64d%I64d", &X, &Y, &M, &N, &L)) { LL a = N - M; LL b = L; LL c = X - Y; d = gcd(a, b); if(c % d != 0) { printf("Impossible\n"); continue; } a /= d; b /= d; c /= d; extend_gcd(a, b, x, y); LL t = c * x % b; if(t < 0) t += b; printf("%I64d\n", t); } return 0; }
#include <iostream> typedef long long LL; using namespace std; LL X, Y, M, N, L; void extend_gcd(LL a, LL b, LL &d, LL &x, LL &y) { if(b == 0) { d = a; x = 1; y = 0; } else { extend_gcd(b, a % b, d, y, x); y -= x * (a / b); } } int main() { while(cin >> X >> Y >> M >> N >> L) { LL d, x, y; extend_gcd(N - M, L, d, x, y); if((X - Y) % d == 0) { LL p = L / d; x = (X - Y) / d * x; x = (x % p + p) % p; //防止x为负值 cout << x << endl; } else cout << "Impossible" << endl; } return 0; } /* d为N-M和L的最大公约数,x为(N-M)/d对L/d的逆元,即((N-M)/d) * x ≡ 1(mod L/d), 即((N-M)/d) * x + (L / d)* y = 1的一组解, 所以((N-M)/d) * x + (L / d)* y = (X-Y)/d的一组解为x0 = (X-Y)/d * x. 这也是(N - M) * x+ L * y = (X - Y)的一组解。 */
标签:数学
原文地址:http://blog.csdn.net/lyhvoyage/article/details/40189481