原式 ax + by = c => ax1 + by1 = gcd(a,b);
a,b,c为任意整数,d = gcd(a,b),则 ax1 + by1 = d 的一组解是(x1,y1),c是gcd(a,b)的倍数时,其中的一组解为(x1*c/d,y1*c/d);c不是gcd(a,b)的倍数时,无解
青蛙的约会,就是一道例题
按照题意很容易列举出等式:(x+ms) - (y+ns) = k*l; (k=1.....n) 变形到 扩展欧几里得公式 即可;
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> using namespace std; #define MIN INT_MIN #define MAX INT_MAX #define N 204 #define LL long long int gcd(int n,int m) { int r; while(m!=0) { r = n%m; n = m; m = r; } return n; } void exgcd(LL a,LL b,LL &x1,LL &y1) { if(b==0) { x1=1; y1=0; return ; } exgcd(b,a%b,x1,y1); LL t; t=x1; x1=y1; y1=t-a/b*y1; } int main() { LL n,m,x,y,s,l,x1,y1; scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l); //推导过程如下 //(x+ms) - (y+ns) = k*l;(k=1.....n) //x-y + ms - ns = k*l; //(n-m)s + k*l = x-y; // a*s + k*b = c; ->gcd(a,b); // s为所求最短步数 LL st = gcd(n-m,l); if((x-y)%st!=0) puts("Impossible"); else { LL a = n-m; LL b = l; LL c = x-y; a /= st; b /= st; c /= st; exgcd(a,b,x1,y1); x1 = x1 * c; // printf("%lld %lld\n",x1,y1); //y1 = y1 * c; //其中一组解(x1*c/st,y1*c/st)->前提c是gcd(a,b)的倍数 LL int tt = x1 % l; //LL int tt = y1*c/st; if(tt < 0) { tt += l; } printf("%d\n",tt); } return 0; }
POJ 1061 青蛙的约会 (扩展欧几里得)
时间: 2024-10-24 23:31:39