Algorithm. IdaStar():Output. The shortest path, path, and its cost, C, if a path exists,and NOT_FOUND, otherwise.Method.1234567C←h(s)path←[s]while truet←Search(path,0,C)if t=FOUND then return (path,C)if t=∞ then return NOT_FOUNDC←tSub-Algorithm. Search(path,g,C):Input. The current path, path, its cost, g, and search limit C.Output. FOUND, if the target node has been reached; ∞, if allreachable nodes have been explored; otherwise, the minimumtotal cost, t, among nodes not yet explored.Method.12345678910111213node←the last element in pathf←g+h(node)if f>C then return fif node is the target then return FOUNDmin←∞for each child of node doif child not in path thenappend child to patht←Search(path,g+Cost(node,child),C)if t=FOUND then return FOUNDif t<min then min←tremove the last element of pathreturn min
因此,可以直接枚举所有可行的 k,判断是否存在这样一组整数解.枚举 k 时,上界通过 y<Emax 判断.
每次得到一组答案时,都将分母的上界 Me 调整到当前答案中的最大分母减一.
另外,实现中,直接记录了 ba−dc 和 C−g 的取值,前者的分子和分母分别存储在变量 a 和 b 中,后者则存储为变量 d.
示例代码
#include<cmath>#include<iostream>#include<numeric>#include<vector>int max_e = 1e7;
std::vector<int> ans;
std::vector<int> current;
longlonggcd(longlong x, longlong y){ return y ? gcd(y, x % y) : x; }
booldfs(int d, longlong a, longlong b, int e){
longlong _gcd = gcd(a, b);
a /= _gcd;
b /= _gcd;
bool solved = false;
if (d == 2) {
for (int k = 4 * b / (a * a) + 1;; ++k) {
longlong delta = a * a * k * k - 4 * b * k;
longlong t = std::sqrt(delta + 0.5l);
longlong x = (a * k - t) / 2;
longlong y = (a * k + t) / 2;
if (y > max_e) break;
if (!t || t * t != delta || (a * k - t) % 2 != 0) continue;
ans = current;
ans.push_back(x);
ans.push_back(y);
max_e = y - 1;
solved = true;
}
} else {
int e1 = std::max(e + 1, int((b + a - 1) / a));
for (; e1 <= d * b / a && e1 <= max_e; e1++) {
current.push_back(e1);
// a/b - 1/e
solved |= dfs(d - 1, a * e1 - b, b * e1, e1);
current.pop_back();
}
}
return solved;
}
intsolve(int a, int b){
if (b % a == 0) {
ans.push_back(b / a);
return1;
}
for (int lim = 2; lim <= 100; lim++)
if (dfs(lim, a, b, 1)) return lim;
return-1;
}
intmain(){
int a, b;
std::cin >> a >> b;
solve(a, b);
for (auto x : ans) std::cout << x << ' ';
std::cout << std::endl;
return0;
}