poj 1061 青蛙的約會(拓展歐幾里得演算法)
阿新 • • 發佈:2018-12-13
【題目】
【題意】
兩隻青蛙在給定長度的數軸上運動,給定初始位置和跳躍每次的長度,問在什麼時候兩隻青蛙能相遇。
【思路】
根據題意有x+mt=y+nt+kl,t表示跳躍次數。變化一下得到式子x-y=(n-m)*t+k*l,形如ax+by=c,因此考慮使用拓展歐幾里得演算法,求出最小的跳躍次數。
【程式碼】
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cstdlib> #include <map> #include <list> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <iostream> #define mem(a) memset(a,0,sizeof(a)) #define go(i,a,b) for(int i=a;i<=b;i++) #define og(i,a,b) for(int i=a;i>=b;i--) using namespace std; const int N=1e6; const int inf=0x3f3f3f3f; typedef long long ll; typedef unsigned long long ull; ll exgcd(ll a,ll b,ll &x,ll &y) { if(!b) { x=1;y=0; return a; } int r=exgcd(b,a%b,x,y); int t=x; x=y; y=t-a/b*y; return r; } int main() { ll x,y,m,n,l,a,b,c,d; scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l); b=n-m; a=x-y; c=exgcd(b,l,x,y); if(a%c) printf("Impossible\n"); else { x=x*a/c; x=(x%l+l)%l; printf("%d\n",x); } return 0; }