P5656 【模板】二元一次不定方程(exgcd)

题目传送门

题意: 给定不定方程ax+by=c。

若该方程无整数解,输出 -1
若该方程有整数解,且有正整数解,则输出其正整数解的数量,所有正整数解中 x 的最小值,所有正整数解中 y 的最小值,所有正整数解中 x 的最大值,以及所有正整数解中 y 的最大值
若方程有整数解,但没有正整数解,你需要输出所有整数解中 x 的最小正整数值, y 的最小正整数值

正整数解即为 x,y。x,y 均为正整数的解, 0 不是正整数
整数解即为 x,y,x,y 均为整数的解
x 的最小正整数值即所有 x 为正整数的整数解中 x 的最小值,y 同理。

思路 exgcd。。代码后有注释里。

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define vi vector<int>
#define mii map<int,int>
#define pii pair<int,int>
#define ull unsigned long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
char *fs,*ft,buf[1<<20];
#define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++;
inline int read(){
int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=gc();}
return x*f;}
using namespace std;
const int N=2e5+5;
const int inf=0x7fffffff;
const int mod=1e9+7;
const double eps=1e-6;
int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}
void exgcd(int a,int b,int &x,int &y)//exgcd模板
{
    if(!b)
    {
        x=1;
        y=0;
        return ;
    }
    exgcd(b,a%b,x,y);
    int tmp=x;
    x=y;
    y=tmp-a/b*y;
    return ;
}
signed main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int a,b,c;
        a=read();b=read();c=read();
        if(c%gcd(a,b)!=0)//裴蜀定理,无解的情况
        {
            cout<<-1<<endl;
            continue;
        }
        int x,y;
        int g=gcd(a,b);
        a/=g;b/=g;c/=g;
        exgcd(a,b,x,y);//求ax+by=1时,x,y的一个特解
        x*=c;y*=c;//ax+by=c的解
        int rx,ry;
        if(x>0&&x%b!=0)//通解是x+k*b,证明可以搜
            rx=x%b;//最小正整数解
        else
            rx=x%b+b;
        if(y>0&&y%a!=0)
            ry=y%a;
        else
            ry=y%a+a;
        int mx=(c-b*ry)/a,my=(c-a*rx)/b;//最大正整数解是当另一个最小
        int cnt=0;
        if(mx>0&&my>0)//正整数解的个数
        {
            cnt=(mx-rx)/b+1;
        }
        if(cnt)
            cout<<cnt<<' '<<rx<<' '<<ry<<' '<<mx<<' '<<my<<endl;
        else
            cout<<rx<<' '<<ry<<endl;
    }
}

原创文章 144 获赞 13 访问量 8679

猜你喜欢

转载自blog.csdn.net/Joker_He/article/details/105851392