康熙的难题(exgcd,洛谷P1516 青蛙的约会)
x+km≡y+kn(modl)
x+km−(y+kn)=lz,z∈Z
x−y+k(m−n)−lz=0
k(m-n)-lz=-(x-y)
设S=x-y,W=n-m
kW+lz=S(exgcd,求k)
//我的代码
#include<iostream>
#define ll long long
using namespace std;
ll ans,x,y,k;
void exgcd(long long a,long long b)
{
if(b==0)
{
x=1;
y=0;
ans=a;
return;
}
exgcd(b,a%b);
k=x;
x=y;
y=k-a/b*y;
return;
}
int main()
{
ll x1,y1,m,n,l;
cin>>x1>>y1>>m>>n>>l;
ll a=n-m,b=x1-y1;
if(a<0)
{
a=-a;
b=-b;
}
exgcd(a,l);
if(b%ans)
cout<<"Impossible";
else
cout<<(b/ans*x%(l/ans)+l/ans)%(l/ans);
return 0;
}
//std代码
#include <iostream>
using namespace std;
long long ex_gcd(long long a, long long b, long long &x, long long &y){
if (b == 0){
x = 1; y = 0; return a;
}
long long d = ex_gcd(b, a % b, x, y);
long long t;
t = x; x = y; y = t - (a / b) * x;
return d;
}
int main(){
long long x0, y0, m, n, l, a, b, c, x, y;;
cin>>x0>>y0>>m>>n>>l;
a = m - n;
b = l;
c = y0 - x0;
if (a < 0)
{
a = -a; c = -c;
}
long long d = ex_gcd(a, b, x, y);
if (m == n || c % d != 0) cout<<"Impossible"<<endl;
else{
b /= d;
c /= d;
long long t = c * x;
cout<<(t % b + b) % b<<endl;
}
return 0;
}