题意:给你两个砝码的质量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;
}