poj1061
青蛙的約會
Description 兩只青蛙在網上相識了,它們聊得很開心,于是覺得很有必要見一面。它們很高興地發現它們住在同一條緯度線上,于是它們約定各自朝西跳,直到碰面為止。可是它們出發之前忘記了一件很重要的事情,既沒有問清楚對方的特征,也沒有約定見面的具體位置。不過青蛙們都是很樂觀的,它們覺得只要一直朝著某個方向跳下去,總能碰到對方的。但是除非這兩只青蛙在同一時間跳到同一點上,不然是永遠都不可能碰面的。為了幫助這兩只樂觀的青蛙,你被要求寫一個程序來判斷這兩只青蛙是否能夠碰面,會在什么時候碰面。
我們把這兩只青蛙分別叫做青蛙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 Source |
求解不定方程的最小解
先求
M=exgcd(n-m,l,&,&Y)
如果(x-y)%M==0則有解
令s=l/M X=X*(x-y)/M
解為 (x%s+s)%s 如果是負數那么加l或s
code
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <algorithm>
#include <iomanip>
#define lld __int64
using namespace std;
lld gcd(lld a,lld b)
{
if(b==0) return a;
else return gcd(b,a%b);
}
lld exgcd(lld a,lld b,lld &x,lld &y)
{
lld p,q;
if(b==0)
{
x=1;
y=0;
return a;
}
p=exgcd(b,a%b,x,y);
q=x;
x=y;
y=q-a/b*y;
return p;
}
int main()
{
lld n,m,x,y,l;
lld X,Y,M;
lld s,res;
while(scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l)!=EOF)
{
//if(n<m)
// {
// M=n;
// n=m;
// m=M;
//}
M=exgcd(n-m,l,X,Y);
if((x-y)%M||n==m)
{
printf("Impossible\n");
}
else
{
s=l/M;
X=X*((x-y)/M);
res=(X%s+l+l+l+l)%s;
printf("%lld\n",res);
}
}
return 0;
}
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <algorithm>
#include <iomanip>
#define lld __int64
using namespace std;
lld gcd(lld a,lld b)
{
if(b==0) return a;
else return gcd(b,a%b);
}
lld exgcd(lld a,lld b,lld &x,lld &y)
{
lld p,q;
if(b==0)
{
x=1;
y=0;
return a;
}
p=exgcd(b,a%b,x,y);
q=x;
x=y;
y=q-a/b*y;
return p;
}
int main()
{
lld n,m,x,y,l;
lld X,Y,M;
lld s,res;
while(scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l)!=EOF)
{
//if(n<m)
// {
// M=n;
// n=m;
// m=M;
//}
M=exgcd(n-m,l,X,Y);
if((x-y)%M||n==m)
{
printf("Impossible\n");
}
else
{
s=l/M;
X=X*((x-y)/M);
res=(X%s+l+l+l+l)%s;
printf("%lld\n",res);
}
}
return 0;
}