标签:
Description
Input
Output
Sample Input
1 2 3 4 5
Sample Output
4
题目描述: 有一个首尾相连的环形数轴,规定一个原点0,两只青蛙的起跳位置分别问x和y,两个青蛙每跳一次所花时间都是1秒,跳一次的前进距离分别问m和n,
问两只青蛙是否会相遇,相遇所花的最短时间是多少
解题思路:假设k圈之后两个青蛙相遇,这时候都跳了T步
那么(X+TM)-(Y+TN) = KL;(K = 0, 1, 2, 3, ……, n);
化简为(N-M)*T + L*K = X - Y;
设a = N - M;
b = L;
c = X - Y:
相当于解方程a*x + b*y = c;
如果gc = gcd(a, b) 是c的约数,那么这个方程有解,否则无解
一组解为x0 = x*c/gc; y0 = y*c/gc;
通解为x = x0 + b/gc*t; y = y0-a*gc*t;
上代码:
#include <stdio.h> #define LL long long LL exgcd(LL a, LL b, LL &x, LL &y) { if(b == 0) { x = 1; y = 0; return a; } else { LL gc = exgcd(b, a%b, x, y); LL tmp = x; x = y; y = tmp - a/b*y; return gc; } } int main() { LL X, Y, M, N, L; LL x, y; while(~scanf("%lld%lld%lld%lld%lld", &X, &Y, &M, &N, &L)) { LL a = N - M; LL b = L; LL c = X - Y; LL gc = exgcd(a, b, x, y); if(c%gc) printf("Impossible\n"); else { c /= gc; LL t = (c*x%b+b)%b; printf("%lld\n", t); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/rain-1/p/4887294.html