洛谷P1516 青蛙的约会

题目描述

两只青蛙在网上相识了,它们聊得很开心,于是觉得很有必要见一面。它们很高兴地发现它们住在同一条纬度线上,于是它们约定各自朝西跳,直到碰面为止。可是它们出发之前忘记了一件很重要的事情,既没有问清楚对方的特征,也没有约定见面的具体位置。不过青蛙们都是很乐观的,它们觉得只要一直朝着某个方向跳下去,总能碰到对方的。但是除非这两只青蛙在同一时间跳到同一点上,不然是永远都不可能碰面的。为了帮助这两只乐观的青蛙,你被要求写一个程序来判断这两只青蛙是否能够碰面,会在什么时候碰面。

我们把这两只青蛙分别叫做青蛙A和青蛙B,并且规定纬度线上东经0度处为原点,由东往西为正方向,单位长度1米,这样我们就得到了一条首尾相接的数轴。设青蛙A的出发点坐标是x,青蛙B的出发点坐标是y。青蛙A一次能跳m米,青蛙B一次能跳n米,两只青蛙跳一次所花费的时间相同。纬度线总长L米。现在要你求出它们跳了几次以后才会碰面。

输入输出格式

输入格式:

 

输入只包括一行5个整数x,y,m,n,L

其中0<x≠y < =2000000000,0 < m、n < =2000000000,0 < L < =2100000000。

 

输出格式:

 

输出碰面所需要的天数,如果永远不可能碰面则输出一行"Impossible"。

 

输入输出样例

输入样例#1: 复制
1 2 3 4 5
输出样例#1: 复制
4

说明

各个测试点2s

 $$x+S*m\%L-(y+S*n)\%L=0$$

$$x-y+S*(m-n)+L*p=0$$

$$S*(m-n)+L*p=y-x$$

 

这样就化简成了ax+by的形式

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<algorithm>
 4 #define LL long long 
 5 using namespace std;
 6 const LL MAXN=400001;
 7 inline LL read()
 8 {
 9     char c=getchar();LL x=0,flag=1;
10     while(c<'0'||c>'9')    {if(c=='-')    flag=-1;c=getchar();}
11     while(c>='0'&&c<='9')    x=x*10+c-48,c=getchar();return x*flag;
12 }
13 LL gcd(LL a,LL b)
14 {
15     return b==0?a:gcd(b,a%b);
16 }
17 inline void IM()
18 {
19     printf("Impossible");
20     exit(0);
21 }
22 LL x,y;
23 LL exgcd(LL a,LL b,LL &x,LL &y)
24 {
25     if(b==0)    {    x=1,y=0;return a;}
26     LL r=exgcd(b,a%b,x,y);
27     LL tmp=x;
28     x=y;y=tmp-(a/b)*y;
29     return r;
30 }
31 LL bgx,bgy,stepm,stepn,L;
32 int main()
33 {
34     bgx=read(),bgy=read(),stepm=read(),stepn=read(),L=read();
35     if(stepm-stepn<0)    swap(stepm,stepn),swap(bgx,bgy);
36     if((bgy-bgx)%gcd((stepm-stepn),L)!=0)    IM();
37     
38     LL r=exgcd(stepm-stepn,L,x,y);
39     x=x*(bgy-bgx)/r,
40     L=L/gcd(stepm-stepn,L);
41     
42     x=(x%L+L)%L;//处理x可能为负 
43     printf("%lld",x);
44     return 0;
45 }

 

 

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
#define LL long long
inline LL read()
{
    char ch=getchar();LL x=0,f=1;
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0',ch=getchar();}
    return x*f;
}
LL x,y;
LL exgcd(LL a,LL b,LL &x,LL &y)
{
    if(b==0)
    {
        x=1;y=0;
        return a;
    }
    LL r=exgcd(b,a%b,x,y);
    LL tmp=x;x=y;y=tmp-a/b*y;
    return r;
}
int main()
{
    LL x0=read(),y0=read(),m=read(),n=read(),L=read();
    if(m<n) swap(x0,y0),swap(n,m);
    LL gcd=exgcd(m-n,L,x,y);
    if( (y0-x0)%gcd!=0 ){printf("Impossible");return 0;}
    x=x*(y0-x0)/gcd;L=abs(L/gcd)*(y0-x0);
    x=(x%L+L)%L;//处理x可能为负 
    printf("%lld",x);
    return 0;
}

 

posted @ 2017-10-24 21:07  自为风月马前卒  阅读(436)  评论(0编辑  收藏  举报

Contact with me