POJ 1061 青蛙的约会(拓展欧几里得)
| Time Limit: 1000MS | Memory Limit: 10000KB | 64bit IO Format: %I64d & %I64u |
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
题目大意:
2仅仅青蛙分别站在x和y处,每次分别能跳m和n米,维度线总长L,求跳了几次后会碰面。若永远不能碰面,则输出-1.解题思路:
我们能够把题目理解成这个意思
设t为跳的次数,k为某一个整数
(x+mt)-(y+nt)=Lk
(x-y)-(n-m)t=Lk
(n-m)t+Lk=(x-y)
当中(n-m)、L、(x-y)为已知。t和k未知,t为所求。
所以我们就把这道题转化成了拓展欧几里得求t。
參考代码:
#include<map>
#include<stack>
#include<queue>
#include<cmath>
#include<vector>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const double eps=1e-10;
const int INF=0x3f3f3f3f;
const int MAXN=1100;
typedef long long LL;
LL m,n,x,y,L;
LL gcd(LL a,LL b)
{
return b?gcd(b,a%b):a;
}
void exgcd(LL a,LL b,LL c,LL& ansx,LL& ansy)
{
if(b==0)
{
c=a;
ansx=1;
ansy=0;
}
else
{
exgcd(b,a%b,c,ansy,ansx);
ansy-=ansx*(a/b);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif // ONLINE_JUDGE
while(scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&L)!=EOF)
{
LL a=n-m,b=L,c=x-y;
LL g=gcd(a,b);
if(c%g||m==n)
{
printf("Impossible\n");
continue;
}
LL ansx,ansy;
a/=g;
b/=g;
c/=g;
exgcd(a,b,c,ansx,ansy);//a*ansx+b*ansy=c
ansx*=c;
ansx%=b;
while(ansx<0)//ansx可能为负数
ansx+=L;
printf("%lld\n",ansx);
}
return 0;
}
浙公网安备 33010602011771号