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

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

解题思路:扩展欧几里得和小知识点的运用。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<ll,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 1e5+10;
const ull base = 131;
const ll mod =  1e9+7;
const double PI = acos(-1.0);
const double eps = 1e-4;

inline int read(){
    
    int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){
    
    if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
    
    x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){
    
    string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){
    
    s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){
    
    str+=s;s=getchar();}return str;}
int random(int n){
    
    return (int)(rand()*rand())%n;}
void writestring(string s){
    
    int n = s.size();for(int i = 0;i < n;i++){
    
    printf("%c",s[i]);}}
ll fast_power(ll a,ll p){
    
    
    ll ans = 1;
    while(p){
    
    
        if(p&1) ans = (ans*a)%mod;
        p >>= 1;
        a = (a*a)%mod;
    }
    return ans;
}


void exgcd(ll a,ll b,ll &x,ll &y){
    
    
    if(b == 0){
    
    
        x = 1;y = 0;
        return;
    }
    exgcd(b,a%b,y,x);
    y -= a/b*x;
}
void fun(int a,int b,int c){
    
    
    for(int x = 1;x <= c;x++){
    
    
        for(int y = 1;y <= c;y++){
    
    
            if(x*a+y*b == c){
    
    
                printf("%6d%6d\n",x,y);
            }
        }
    }
}



void solve(ll a,ll b,ll c){
    
    
    ll x,y;
    exgcd(a,b,x,y);
    ll d = __gcd(a,b);
    if(c%d){
    
    
        puts("-1");
        return;
    }

    ll p1 = b/d,p2 = a/d;
    x = x*c/d;//求出通解的x
    y = y*c/d;//求出通解的y
    ll min_x = (x%p1+p1)%p1,min_y = (y%p2+p2)%p2;
    //这一步可以求出x和y最小的非负整数
    if(min_x == 0) min_x = p1;//如果为0的话,需要加上p1
    if(min_y == 0) min_y = p2;

    ll max_x = (c-b*min_y)/a;//根据最小的y和x求出相对应的最大x和y
    ll max_y = (c-a*min_x)/b;//

    if(max_y <= 0){
    
    //表示答案只能为负数
        printf("%lld %lld\n",min_x,min_y);
    }else {
    
    
        ll cnt = (max_x-min_x)/p1+1;//统计出个数
        printf("%lld %lld %lld %lld %lld\n",cnt,min_x,min_y,max_x,max_y);
    }
}
int main(){
    
    
    //srand((unsigned)time(NULL));
    //freopen(  "out.txt","w",stdout);
    int t = read();
    while(t--){
    
    
        ll a = read(),b = read(),c = read();
        solve(a,b,c);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42868863/article/details/114701250