“完美”?
I'm rofor.
for(;;;); :-)
RoFoR [AT] YaHoO [DoT] CN
#include <stdio.h> #define N 1000000 #define FLOOR(a, b) ((a) / (b) + ((a) % (b) != 0)) #define GET_E(a, b) FLOOR(b, a) #define GET_H(c, d, e) ((a) * (e) / (b)) struct { int c, d, e, g; } stack[N], *top; int ans[N], cur[N], clen; /* 化简分数 a/b 到最简形式 */ void simply(int *a, int *b) { int c = *a, d = *b; while (d != 0) { int t = d; d = c % d; c = t; } *a /= c; *b /= c; } /* 假设剩下的分数为a/b,将a/b所有最短序列小于limit的e入栈 */ void push_child(int a, int b, int g, int limit) { int e, emin, emax; emin = GET_E(a, b); if (clen != -1 && emin <= cur[clen]) emin = cur[clen] + 1; emax = GET_E(a, (limit - g) * b); for (e = emax - 1; e >= emin; --e) { top->c = a * e - b; top->d = e * b; if (top->c > 0 && top->d > 0) { simply(&top->c, &top->d); top->e = e; top->g = g; ++top; } } } /* 迭代加深的A*搜索 */ int idastar(int a, int b) { int limit, i; simply(&a, &b); ans[0] = -1; top = stack; limit = GET_H(a, b, GET_E(a, b)) - 1; while (ans[0] == -1 && ++limit < N) { clen = -1; push_child(a, b, 0, limit); /* 以limit为长度限制,搜索 */ while (top > stack) { --top; clen = top->g; cur[clen] = top->e; if (cur[clen] < top->d && (ans[0] == -1 || top->d < ans[clen + 1])) { for (i = 0; i <= clen; ++i) ans[i] = cur[i]; ans[clen + 1] = top->d; } else push_child(top->c, top->d, clen + 1, limit); } } return ans[0] != -1 ? limit : 0; } int main(void) { int i, a, b, len; while (scanf("%d%d", &a, &b) != EOF) { if ((len = idastar(a, b)) == 0) { puts("can't find answer"); continue; } printf("%d", ans[0]); for (i = 1; i < len; ++i) printf(" %d", ans[i]); } return 0; }