hihocoder 扩展欧几里得

来源:互联网 发布:运营数据分析的步骤 编辑:程序博客网 时间:2024/05/20 13:38

题意:

就是纯的扩展欧几里得;

理解:

题目有些地方可能我不太理解;
主要是在正负关系上吧;

扩展欧几里得:
通过做这道题,我深入的探讨了下扩展欧几里得;
首先:

根据 ax + by = gcd(a, b) 一定有整数解可知:有:ax1 + by1 = gcd(a, b)即:bx2 + (a%b)y2 = gcd(b, a%b)即:bx2 + (a - [a/b] * b)y2 =  ax1 + by1   ([]表示向下取整)即:ay2 + (x2 - [a/b] * y2)b = ax1 + by1即:x1 = y2, y1 = x2 - [a/b] * y2当gcd(a, b) = d时, 有 b = 0, 即 a = d;即 dx + 0 * y = d则:x = 1,而 y 可以设为任意值;

通过上述推导,我们可以看出,x 和 y 一定能求出一组整数解;
那么重要的是,我们不是只要一组无意义的解;
一般都是找一个最小正整数解 x;
那么又继续推导:

如果我们有一组解为 x0,y0则:ax0 + by0 = gcd(a, b) 设我们有另一组解为 x1, y1x1 = x0 + m1y1 = y0 + m2则:a(x0 + m1) + b(y0 + m2) = gcd(a, b)则:am1 + bm2 = 0则:m1 / m2 = - b / a因为 a 和 b 有共同的因子 d则:m1 / m2 = - (b/d) / (a/d)那么可以知道当前 m1 和 m2 最小的步长为:m1 = b/dm2 = -(a/d)但是由于是找最小的正整数解 x所以一般:x = x0 + b/dy = y0 - a/d

推导到这儿就很明显了;
只要求出一组 x0 和 y0 就可以求得一个最小正整数解了;

但是有个问题我没有推导;
就是在 d 为负数是是否可以把 d 和 a 、b 都当做正整数来看待;

此题代码如下:

#include <cstdio>#include <cstring>#include <cmath>#include <ctime>#include <iostream>#include <algorithm>#include <vector>#include <string>#include <map>#include <set>#include <queue>#include <stack>using namespace std;typedef long long LL;typedef pair<int, int> PII;const double MIN_INF = 1e-7;const int MAX_INF = (1e9) + 7;#define X first#define Y secondLL exgcd(LL a, LL b, LL &x, LL &y) {    LL d;    if (b != 0) {        d = exgcd(b, a % b, y, x);        y -= (a / b) * x;    }    else {        x = 1, y = 0;        return a;    }    return d;}int main() {    LL s1, s2, v1, v2, m;    cin >> s1 >> s2 >> v1 >> v2 >> m;    LL a = v1 - v2, b = m, c = s2 - s1;    LL x, y;    LL d = exgcd(a, b, x, y);    if (c == 0) {        cout << 0 << endl;        return 0;    }    if (c % d != 0) {        cout << -1 << endl;        return 0;    }    x *= (c / d);    LL g = b / d;    if (g < 0) {        if (x < 0) {            x = x % g - g;        }        else {            x = x % (-g);        }    }    else {        if (x < 0) {            x = x % g + g;        }        else {            x = x % g;        }    }    cout << x << endl;    return 0;}
0 0
原创粉丝点击