Luogu1516 青蛙的约会

https://www.luogu.com.cn/problem/P1516

扩展欧几里得算法(\(exgcd\)

\[ (x+mt)-(y+nt)=pl \\ (n-m)t+lp=x-y \]

\(a=n-m,b=l,d=x-y\)

\(exgcd\)一下

\(b/gcd(a,b)\)取模,可以得到最小整数解

\(c=gcd(a,b)\)

\(a/c·x+b/c·y=d/c\)

\(b/c\)值相同的数均可取

#include<iostream>
#include<cstdio>
#define int long long
using namespace std;
int n,m,x,y,xx,yy,l,a,b,c,d,x0,y0;
int exgcd(int a,int b,int &x,int &y)
{
    if (!b)
    {
        x=1;
        y=0;
        return a;
    }
    int r=exgcd(b,a%b,x,y);
    int tmp=x;
    x=y;
    y=tmp-a/b*y;
    return r;
}
signed main()
{
    scanf("%lld%lld%lld%lld%lld",&xx,&yy,&m,&n,&l);
    if (xx==yy)
    {
        cout << "0"  << endl;
        return 0;
    }
    if (m==n)
    {
        cout << "Impossible" << endl;
        return 0;
    }
    if (n<m)
    {
        swap(n,m);
        swap(xx,yy);
    }
    a=n-m;
    b=l;
    d=xx-yy;
    c=exgcd(a,b,x,y);
    if (d%c!=0)
    {
        cout << "Impossible" << endl;
        return 0;
    }
    x0=d/c*x;
    y0=d/c*y;
    int g=l/c;
    x0=(x0%g+g)%g;
    cout << x0 << endl;
    return 0;
}
posted @ 2020-07-20 11:58  GK0328  阅读(98)  评论(0编辑  收藏  举报