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

题目链接

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

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

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

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

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

 1/* ***********************************************
 2Author :111qqz
 3Created Time :Thu 13 Oct 2016 04:23:13 PM CST
 4File Name :code/poj/2142.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31LL a,b,d;
32LL exgcd( LL a,LL b,LL &x,LL &y)
33{
34    if (b==0)
35    {
36	x = 1;
37	y = 0;
38	return a;
39    }
40    LL ret = exgcd(b,a%b,x,y);
41    LL tmp = x;
42    x = y;
43    y = tmp - a/b*y;
44    return ret;
45}
46LL num ( LL x)
47{
48    if (x<0) return -x;
49    return x;
50}
51LL cal( LL x,LL y)
52{
53    return a*num(x)+b*num(y);
54}
55bool ok( LL x,LL y,LL gx,LL gy)
56{
57    if (num(x)+num(y)>num(x+gx)+num(y-gy)) return true;
58    if (num(x)+num(y)==num(x+gx)+num(y-gy)&&cal(x,y)>cal(x+gx,y-gy)) return true;
59    return false;
60}
61bool ok2( LL x,LL y,LL gx,LL gy)
62{
63    if (num(x) + num(y) > num(x-gx) + num(y+gy)) return true;
64    if (num(x) + num(y) ==num (x-gx) + num(y+gy)&&cal(x,y)>cal(x-gx,y+gy)) return true;
65    return false;
66}
67int main()
68{
69	#ifndef  ONLINE_JUDGE 
70	freopen("code/in.txt","r",stdin);
71  #endif
72	while (~scanf("%lld%lld%lld",&a,&b,&d))
73	{
74	    if (a==0&&b==0&&d==0) break;
75	    LL x,y;
76	    LL gcd = exgcd(a,b,x,y);
77	    x = x * d/gcd;
78	    y = y * d/gcd;
79	    LL gx = b/gcd;
80	    LL gy = a/gcd;
81	    while (ok(x,y,gx,gy))
82	    {
83		x = x + gx;
84		y = y - gy;
85	    }
86	    while ( ok2(x,y,gx,gy))
87	    {
88		x = x-gx;
89		y = y+gy;
90	    }
91	    printf("%lld %lld\n",num(x),num(y));
92	}
93  #ifndef ONLINE_JUDGE  
94  fclose(stdin);
95  #endif
96    return 0;
97}