Luogu_P1516 [frog] solution to a problem dating exgcd

Topic links: https://www.luogu.org/problem/P1516

It can be drawn by the title:

  x + m = k * y + k * n (v l)

The mod l into the equation:

  (x-y)=(n-m)*k+l*t

Xy nm is provided as set w c

then

  k*w + l*t = c

Then you can use exgcd be solved.

First solved

  k*w + l*t = d = gcd(w,l) 

Then multiply the answer c / d can be obtained up.

But is not the optimal solution, there is a fairy formula, which is the last line of code statistics answer.

Taking a mold.

code show as below:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll X,Y,m,n,l,x,y;
ll exgcd(ll a,ll b,ll &x,ll &y){
    if(!b){
        x=1;y=0;
        return a;
    }
    ll ans=exgcd(b,a%b,x,y);
    ll z=x;
    x=y;
    y=z-y*(a/b);
    return ans;
}
int main()
{
    scanf("%lld%lld%lld%lld%lld",&X,&Y,&m,&n,&l);
    ll k=n-m,s=X-Y;
    if(k<0){
        k=-k;s=-s;
    }
    ll ans=exgcd(k,l,x,y);
    if(s%ans!=0) printf("Impossible\n");
    else printf("%lld\n",(x*(s/ans)%(l/ans)+(l/ans))%(l/ans));
    //system("pause");
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/ChrisKKK/p/11442378.html