1. 程式人生 > >POJ ~ 1061 ~ 青蛙的約會 (擴充套件歐幾里得)

POJ ~ 1061 ~ 青蛙的約會 (擴充套件歐幾里得)

題解

假設答案為a,其實就是求解:x+ma \equiv y+na (mod\quad L),化為(m-n)a + Lk = y-x

對應到ax+by=c中,a = m-n,b = L, c = y-x。x為a,y為k。要求最小的非負整數x。

假設ax+by=c的一組解為(x0,y0),那麼通解為(x0+b't,y0-a't)\qquad a'=a/\gcd \quad b'=b/\gcd

所以最小非負解為(x_0\%b'+b')\%b'

//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long LL;
void exgcd(LL a, LL b, LL& d, LL& x, LL& y)
{
	if (!b) { d=a; x=1; y=0; }
	else { exgcd(b, a%b, d, y, x); y -= x*(a/b); }
}
LL cal(LL a, LL b, LL c)
{
    LL GCD, x0, y0;
    exgcd(a, b, GCD, x0, y0);
    if (c%GCD) return -1;
    LL bb = b/GCD;
    bb = llabs(bb);//GCD可能為負數,需要把bb變為正
    x0 *= c/GCD; y0 *= c/GCD;
    return (x0%bb+bb)%bb;
}
int main()
{
    LL x, y, m, n, L; scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &L);
    LL ans = cal(m-n, L, y-x); /// x+ma ≡ y+na (mod L) => (m-n)a + L*k = y-x;
    if (ans != -1) printf("%lld\n", ans);
    else printf("Impossible\n");
    return 0;
}
/*
1 2 3 4 5
*/