CodeForces787A【exgcd求不定方程解(模板)】

思路:
B+AX=D+CY
=>
AXCY=DB
然后套exgcd保证X,Y都要>=0.

//#pragma comment(linker, "/STACK:102400000,102400000")
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long LL;
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define mem(a, b) memset(a, b, sizeof(a))

/*
exgcd求不定方程的解
Author: keyboarder_zsq
Time: 2017/10/22 18:53
*/
typedef int Elem;
Elem exgcd(Elem a , Elem b, Elem &x, Elem &y){
    if(b == 0){
        x = 1, y = 0;
        return a;
    }
    Elem gcd = exgcd(b, a%b, x, y);
    Elem temp = x;
    x = y;
    y = temp - a/b*y;
    return gcd;
}
//求方程 a*x + b*y = c 的 x 的最小整数解.
//先利用 exgcd 求 a*x + b*y = gcd(a, b) 的x, y的最小整数解。
//然后再乘上去就好了;
Elem Cal(Elem a, Elem b, Elem c){
    Elem x, y, k, t;
    Elem gcd = exgcd(a, b, x, y);

    if(c%gcd!=0) return -1; //不存在解
    x = x * c/gcd;          //由a*x + b*y = gcd(a, b) 转化为 a*x + b*y = c 的解
    k = b/gcd;              //约去c后原来b就变为了b/gcd;
    if(k < 0) k = -k;       //如果b为负数就去绝对值

    x = (x%k + k) % k;      //最小非负整数解
    if(x <= 0) x = x + k;   //最小正整数解

    y = (c - a * x)/b;      //如果对y还有要求,先求出y值在进行判断

    while(y<0){
        x = x + k;
        y = (c - a * x)/b;
    }
    return x;
}

void solve(){
    int a, b, c, d;
    cin>>a>>b>>c>>d;
    if(b > d){
        swap(b, d);
        swap(a, c);
    }
    int tmp;
    tmp = Cal(a, -c, d-b);
    if(tmp == -1){
        puts("-1");
        return;
    }
    printf("%d\n", b+tmp*a);
}

int main(){
    solve();
    return 0;
}

你可能感兴趣的:(codeforces,数论)