POJ青蛙的约会

青蛙的约会
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 114412   Accepted: 23446

 

 

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

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 long long extgcd(long long a, long long b, long long &x, long long &y)
 5 {
 6     long long d, t;
 7     if (b == 0) 
 8     {
 9         x = 1;
10         y = 0;
11         return a; 
12     }
13     d = extgcd(b, a % b, x, y);
14     t = x - a / b * y;
15     x = y;
16     y = t;
17     return d;
18 }
19 int main()
20 {
21     long long x, y, m, n, L, X, Y, d, r;
22     cin >> x >> y >> m >> n >> L
23     d = extgcd(n - m, L, X, Y);
24     r = L / d;
25     if ((x - y) % d) cout << "Impossible" << endl;
26     else cout << ((x - y) / d * X % r + r) % r << endl;
27     return 0;
28 }
 1 #include <cstdio>
 2 typedef long long LL;
 3 
 4 LL gcd( LL a, LL b )
 5 {
 6     return b==0?a:gcd( b, a%b );
 7 }
 8 void exgcd( LL a, LL b, LL &x, LL &y )
 9 {
10     if( b==0 )
11     {
12         x=1, y=0;
13         return ;    
14     }
15     exgcd( b, a%b, x, y );
16     LL t=x;
17     x=y;
18     y=t-a/b*y;
19 }
20 int main( )
21 {
22     LL x, y, m, n, l;
23     LL a, b, c, k1, k2, r;
24     while(scanf( "%lld%lld%lld%lld%lld", &x, &y, &m, &n, &l )!= EOF)
25     {
26         a=n-m; c=x-y; r=gcd(a,l);
27         if(c%r)
28         {
29             printf("Impossible");
30             continue;
31         }
32         a/=r; l/=r; c/=r;
33         exgcd(a, l, k1, k2);
34         LL t = c*k1/l;
35         k1 = c*k1-t*l;
36         if(k1<0) k1 += l;
37         printf( "%lld
", k1 );    
38     }
39     return 0;
40 }
原文地址:https://www.cnblogs.com/mjtcn/p/6850408.html