HDU-2669 Romantic (扩展欧几里得的应用)

题目链接:Problem - 2669 (hdu.edu.cn)

题目:

 题目样例:

 题目思路:

对扩展欧几里得的一个应用:由以下推到的出:

1.a*x+b*y=gcd;      2.a*(x+s1)+b*(y-s2)=gcd;

两式子推导可以得出:

s1比s2==b 比a;

由于题目规定,求的是最小正整数解的x,x有解的情况是a与b互质(gcd==1时);所以当x为负数是需要加上b,同时y减a;

AC:

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
const int N=1e5+5;
int n,a,b,x,y;
int sum[N],ans[N];
string s;
int ex_gcd(int a,int b,int &x,int &y){
    if(b==0){
        x=1;
        y=0;
        return a;
    }
    int d=ex_gcd(b,a%b,x,y); 
    int tmp=x;
    x=y;
    y=tmp-(a/b)*y;
    return d;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    while(cin>>a>>b){
        if(__gcd(a,b)!=1){
            cout<<"sorry"<<endl;
        }else{
            ex_gcd(a,b,x,y);
            while(x<0){
                x+=b;
                y-=a;
            } 
            cout<<x<<" "<<y<<endl;
        }
    }
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/m0_63569670/article/details/127909714