POJ - 1061 青蛙的约会 (扩展欧几里得算法)
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
思路:扩展欧几里得算法。设时间为t,最后在s点相遇。A走了a圈,B走了b圈,
那么我们能够推出: m*t + x = L * a + s。 n*t + y = L * b + s,两式相减得:(m-n) * t + (b - a) * L = y - x,正好是扩展欧几里得的形式求两个可行解,那么对于求最小的解动脑子想想就得到了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
typedef long long ll;
using namespace std;
ll gcd(ll a, ll b) {
	return b?gcd(b, a%b):a;
}
void exgcd(ll a, ll b, ll &x, ll &y) {
	if (b == 0) {
		x = 1;
		y = 0;
		return;
	}
	exgcd(b, a%b, x, y);
	ll t = x;
	x = y;
	y = t - a / b * y;
	return;
}
int main() {
	ll x, y, n, m, l;
	while (scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &l) != EOF) {
		ll a = n-m, b = l, c = x-y, p, q;
		ll g = gcd(a, b);
		if (c % g)  {
			printf("Impossible\n");
			continue;
		}
		a /= g, b /= g, c /= g;
		exgcd(a, b, p, q);
		p *= c;
		ll t = p % b;
		while (t < 0) 
			t += b;
		printf("%lld\n", t);
	}
	return 0;
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号