1. 程式人生 > >青蛙的約會 POJ - 1061 (exgcd)

青蛙的約會 POJ - 1061 (exgcd)

-- 負數 pri math puts sam def end cstring

兩只青蛙在網上相識了,它們聊得很開心,於是覺得很有必要見一面。它們很高興地發現它們住在同一條緯度線上,於是它們約定各自朝西跳,直到碰面為止。可是它們出發之前忘記了一件很重要的事情,既沒有問清楚對方的特征,也沒有約定見面的具體位置。不過青蛙們都是很樂觀的,它們覺得只要一直朝著某個方向跳下去,總能碰到對方的。但是除非這兩只青蛙在同一時間跳到同一點上,不然是永遠都不可能碰面的。為了幫助這兩只樂觀的青蛙,你被要求寫一個程序來判斷這兩只青蛙是否能夠碰面,會在什麽時候碰面。
我們把這兩只青蛙分別叫做青蛙A和青蛙B,並且規定緯度線上東經0度處為原點,由東往西為正方向,單位長度1米,這樣我們就得到了一條首尾相接的數軸。設青蛙A的出發點坐標是x,青蛙B的出發點坐標是y。青蛙A一次能跳m米,青蛙B一次能跳n米,兩只青蛙跳一次所花費的時間相同。緯度線總長L米。現在要你求出它們跳了幾次以後才會碰面。

Input

輸入只包括一行5個整數x,y,m,n,L,其中x≠y < 2000000000,0 < m、n < 2000000000,0 < L < 2100000000。

Output

輸出碰面所需要的跳躍次數,如果永遠不可能碰面則輸出一行"Impossible"

Sample Input

1 2 3 4 5

Sample Output

4

就是一個exgcd板題 關鍵在於推公式
exgcd就是用特解求全部解 找出一個特殊情況就好了
註意答案為負數的情況

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include 
<map> #include <cctype> #include <set> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <cmath> #include <bitset> #define rap(i, a, n) for(int i=a; i<=n; i++) #define rep(i, a, n) for(int i=a; i<n; i++) #define
lap(i, a, n) for(int i=n; i>=a; i--) #define lep(i, a, n) for(int i=n; i>a; i--) #define rd(a) scanf("%d", &a) #define rlld(a) scanf("%lld", &a) #define rc(a) scanf("%c", &a) #define rs(a) scanf("%s", a) #define rb(a) scanf("%lf", &a) #define rf(a) scanf("%f", &a) #define pd(a) printf("%d\n", a) #define plld(a) printf("%lld\n", a) #define pc(a) printf("%c\n", a) #define ps(a) printf("%s\n", a) #define MOD 2018 #define LL long long #define ULL unsigned long long #define Pair pair<int, int> #define mem(a, b) memset(a, b, sizeof(a)) #define _ ios_base::sync_with_stdio(0),cin.tie(0) //freopen("1.txt", "r", stdin); using namespace std; const int maxn = 10010, INF = 0x7fffffff; LL gcd(LL a, LL b) { return b == 0 ? a : gcd(b, a % b); } LL 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 a, b, d, x, y; LL _x, _y, m, n, l; cin >> _x >> _y >> m >> n >> l; if((_x - _y) % gcd(l, n - m)) return puts("Impossible"); exgcd(n - m, l, d, x, y); x *= (_x - _y) / d; x = (x % l + l) % l; cout << x << endl; return 0; }

青蛙的約會 POJ - 1061 (exgcd)