POJ 2142-The Balance(扩展欧几里德)

51 篇文章 0 订阅

题目地址:POJ 2142
题意:有两种类型的砝码质量分别为a和b,要求称出质量为d的物品,要求a的数量x和b的数量y的和x+y最小,若有多个x+y的值,取ax+by最小的。
思路:我们应该求ax+by=d。这里我们应用扩展欧几里德求出ax+by=gcd(a,b),那么ax/gcd(a,b)+by/gcd(a,b)=1,然后求出来特解,令x=x*n,把x转化为最小正值,即x=(x%b+b)%b,求出此时的y=(d-ax)/b,若求出的y是负值,把y变成正的,因为砝码的位置涉及左右之分。同理求出y为最小正值是x的解,然后比较两组的值就好了。。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef __int64 LL;
const int inf=0x3f3f3f3f;
const double pi= acos(-1.0);
const double esp=1e-6;
using namespace std;
int gcd(int a,int b)
{
    while(b!=0){
        int r=b;
        b=a%b;
        a=r;
    }
    return a;
}
void exgcd(int a,int b,int &x,int &y)
{
    if(b==0){
        x=1,y=0;
        return ;
    }
    exgcd(b,a%b,x,y);
    int t=x;
    x=y;
    y=t-(a/b)*y;
}
int main()
{
    int a,b,d;
    int x,y;
    int xx,yy;
    int tx,ty;
    while(~scanf("%d %d %d",&a,&b,&d)){
        if(!a&&!b&&!d) break;
        int G=gcd(a,b);
        a/=G;
        b/=G;
        d/=G;
        exgcd(a,b,x,y);
        xx=x*d;
        xx=(xx%b+b)%b;
        yy=(d-a*xx)/b;
        if(yy<0) yy=-yy;
        ty=y*d;
        ty=(ty%a+a)%a;
        tx=(d-b*ty)/a;
        if(tx<0) tx=-tx;
        if(tx+ty>xx+yy){
            tx=xx;
            ty=yy;
        }
        printf("%d %d\n",tx,ty);
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rocky0429

一块也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值