青蛙的约会

青蛙的约会

有1长为l的环,标号顺时针\(0\)~\(l-1\),有两个动点,从x,y出发,顺时针移动,速度分别为每秒m,n,求两动点相遇所需的时间,\(0<x≠y<=2000000000,0<m,n<=2000000000,0<L<=2100000000\)

转换为数学模型,不难得知问题即解关于k的方程

\[x+km=y+kn(mod\ l) \]

\[k(m-n)=y-x(mod\ l) \]

易知该方程为一元一次同余方程,于是我们用exgcd即可解决这个问题。

参考代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#define il inline
#define ri register
#define ll long long
using namespace std;
il ll exgcd(ll,ll,ll&,ll&),
    equation(ll,ll,ll);
int main(){
    ll x,y,m,n,l,ans;
    scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l);
    ans=equation(m-n,y-x,l);
    if(ans>=0)printf("%lld",ans);
    else puts("Impossible");
    return 0;
}
il ll equation(ll a,ll b,ll c){
    ((a%=c)+=c)%=c,((b%=c)+=c)%=c;
    ll x,y,d(exgcd(a,c,x,y));
    if(b%d)return -1;c/=d;
    ((x%=c)+=c)%=c,x*=(b/d);
    return x%c;
}
il ll exgcd(ll a,ll b,ll &x,ll &y){
    if(!b)return x=1,y=0,a;
    ll d(exgcd(b,a%b,y,x));y-=a/b*x;
    return d;
}

posted @ 2019-05-18 11:36  a1b3c7d9  阅读(133)  评论(0编辑  收藏  举报