题意:有n元钱,有2种单价不同的商品,是否存在一种购买方式使得钱恰好花光,如果有输入任意一种方式,如果没有输出“NO”
题解:可以使用拓展欧几里得快速求解。
1 #include<iostream> 2 using namespace std; 3 #define ll long long 4 ll gcd(ll a, ll b) 5 { 6 return b? gcd(b, a%b) : a; 7 } 8 9 void ex_gcd(ll a, ll b, ll &x, ll &y, ll &d) 10 { 11 if(!b) 12 { 13 x = 1, y = 0, d = a; 14 return ; 15 } 16 ex_gcd(b, a%b, y, x, d); 17 y -= a/b * x; 18 return ; 19 } 20 int main() 21 { 22 ll m, a, b, x, y; 23 cin >> m >> a >> b; 24 ll d = gcd(a, b); 25 if(m%d) 26 { 27 cout << "NO\n"; 28 return 0; 29 } 30 ex_gcd(a, b, x, y, d); 31 x *= m/d, y *= m/d; 32 a /= d, b /= d; 33 if(x<0 && y <0) 34 { 35 cout << "NO\n"; 36 } 37 else if(x < 0) 38 { 39 x = -x; 40 ll z; 41 if(x%b) z = x/b+1; //找到最小的正数x 42 else z = x/b; 43 x = -x + z * b; 44 y = y - z*a; 45 if(y < 0) 46 cout << "NO\n"; 47 else cout << "YES\n" << x << ‘ ‘ << y << endl; 48 } 49 else if(y < 0) 50 { 51 y = -y; 52 ll z; 53 if(y%a) z = y/a+1; 54 else z = y/a; 55 y = -y + z*a; 56 x = x - z*b; 57 if(x < 0) 58 cout << "NO\n"; 59 else cout << "YES\n" << x << ‘ ‘ << y << endl; 60 } 61 else 62 cout << "YES\n" << x << ‘ ‘ << y << endl; 63 return 0; 64 }