[C] 纯文本查看 复制代码
#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;
struct State {
long long beans;
int steps;
};
int minOperations(long long P, long long Q, long long X, int Y) {
queue<State> q;
unordered_set<long long> visited;
q.push({P, 0});
visited.insert(P);
while (!q.empty()) {
State current = q.front();
q.pop();
if (current.beans == Q) {
return current.steps;
}
if (current.steps >= 52) {
continue;
}
// 尝试乘法操作
long long next = current.beans * Y;
if (next <= Q * Y && visited.find(next) == visited.end()) {
visited.insert(next);
q.push({next, current.steps + 1});
}
// 尝试减法操作
if (current.beans >= X) {
next = current.beans - X;
if (next >= 0 && visited.find(next) == visited.end()) {
visited.insert(next);
q.push({next, current.steps + 1});
}
}
}
return -1;
}
int main() {
long long P, Q, X;
int Y;
cin >> P >> Q >> X >> Y;
int result = minOperations(P, Q, X, Y);
if (result != -1) {
cout << result << endl;
} else {
cout << "Failed" << endl;
}
return 0;
}
|