poj_2142_The Balance

这里写图片描述

题意:给你两个砝码的质量A,B。称量一个鬼东东的质量为K,问最少要多少砝码。

题解:易得出
Ax-By=K,用扩展欧几里德算法去元,求出x,y。
求出x,y然后分成两组,求出x可以根据方程推出y,求出y可以根据方程推出x.然后取两组相加的最小值即可.

代码:

#include <stdio.h>      
#include <iostream>      
#include <algorithm>      
#include <sstream>      
#include <stdlib.h>      
#include <string.h>      
#include <limits.h>      
#include <string>      
#include <time.h>      
#include <math.h>      
#include <queue>      
#include <stack>      
#include <map>   
using namespace std;
typedef long long ll;

ll gcd(ll a,ll b){  
    if(b==0) return a;  
    return gcd(b,a % b);  
}  

void ggcd(ll a,ll b,ll &x,ll &y){
    if (b==1){  
        x=1; y=1-a;  
    } else{  
        ll x1,y1;  
        ggcd(b,a%b,x1,y1);  
        x=y1; y=x1-x*(a/b);  
    }  
}  

int main(){  
    ll n,m,k;  
    cin>>n>>m>>k;
    while (n||m||k)  
    {  
        ll g=gcd(n,m);  
        ll x,y,y1,x1;  
        n/=g; m/=g;  
        ggcd(n,m,x,y);
        x1=x*k/g;    
        x1=(x1%m+m)%m;  
        y1=(k/g-n*x1)/m;  
        if (y1<0) y1=-y1;  

        y=y*k/g;  
        y=(y%n+n)%n;
        x=(k/g-m*y)/n;
        if (x<0) x=-x;
        if (x+y>x1+y1) {
            x=x1; y=y1;  
        }
        cout<<x<<" "<<y<<endl;
        cin>>n>>m>>k;
    }
    return 0;
}   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值