poj 2142 The Balance (扩展欧几里得算法)

题目链接

题意:给出a,b,d,分别表示a,b两种刻度的砝码,以及要称量的物体重量为d.现在保证能称量出给定重量的物体,问两种砝码个数的和最小的时候,两种砝码分别有多少。如果有多组解,那么要求weight of(ax + by) 最小。

思路:求特解直接扩展欧几里得...

关键是怎么找到绝对值和最小的。。

我就是两个方向跑了下。。。

一开始因为把weight of (ax+by)  (求得还是绝对值最小)理解成了 ax+by最小。。导致WA了半天。。。。sigh....

/* ***********************************************
Author :111qqz
Created Time :Thu 13 Oct 2016 04:23:13 PM CST
File Name :code/poj/2142.cpp
************************************************ */
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair
using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
LL a,b,d;
LL exgcd( LL a,LL b,LL &x,LL &y)
{
    if (b==0)
    {
	x = 1;
	y = 0;
	return a;
    }
    LL ret = exgcd(b,a%b,x,y);
    LL tmp = x;
    x = y;
    y = tmp - a/b*y;
    return ret;
}
LL num ( LL x)
{
    if (x<0) return -x;
    return x;
}
LL cal( LL x,LL y)
{
    return a*num(x)+b*num(y);
}
bool ok( LL x,LL y,LL gx,LL gy)
{
    if (num(x)+num(y)>num(x+gx)+num(y-gy)) return true;
    if (num(x)+num(y)==num(x+gx)+num(y-gy)&&cal(x,y)>cal(x+gx,y-gy)) return true;
    return false;
}
bool ok2( LL x,LL y,LL gx,LL gy)
{
    if (num(x) + num(y) > num(x-gx) + num(y+gy)) return true;
    if (num(x) + num(y) ==num (x-gx) + num(y+gy)&&cal(x,y)>cal(x-gx,y+gy)) return true;
    return false;
}
int main()
{
	#ifndef  ONLINE_JUDGE 
	freopen("code/in.txt","r",stdin);
  #endif
	while (~scanf("%lld%lld%lld",&a,&b,&d))
	{
	    if (a==0&&b==0&&d==0) break;
	    LL x,y;
	    LL gcd = exgcd(a,b,x,y);
	    x = x * d/gcd;
	    y = y * d/gcd;
	    LL gx = b/gcd;
	    LL gy = a/gcd;
	    while (ok(x,y,gx,gy))
	    {
		x = x + gx;
		y = y - gy;
	    }
	    while ( ok2(x,y,gx,gy))
	    {
		x = x-gx;
		y = y+gy;
	    }
	    printf("%lld %lld\n",num(x),num(y));
	}
  #ifndef ONLINE_JUDGE  
  fclose(stdin);
  #endif
    return 0;
}