本不打算参与,既然老杨也来了,那就凑个热闹。
这题就是个有限状态机而已。可以用有向图穷搜,也可以用树(展开的有向图)穷搜。
这题就是个有限状态机而已。可以用有向图穷搜,也可以用树(展开的有向图)穷搜。
程序代码:
#include<stdio.h> const int v[3] = {12, 8, 5}; const int work[6][2] = {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}; typedef union { char cup[3]; int value; } ST; ST path[367]; int path_count, path_index; int min_count = 368, min_index; int isInPath(ST st) { int i; for(i = 0; i < path_count; i++) if(path[i].value == st.value) return 1; return 0; } void search(ST st) { int i, a, b, c, t; ST tst; path[path_count++] = st; if(st.value == 0x606) { path_index++; if(min_count > path_count){ min_count = path_count; min_index = path_index;} printf("Method #%d: in step %d\n 12L 8L 5L\n------------\n", path_index, path_count - 1); for(i = 0; i < path_count; i++) printf(" %2d %2d %2d\n", path[i].cup[0], path[i].cup[1], path[i].cup[2]); putchar('\n'); path_count--; return; } for(i = 0; i < 6; i++) { a = st.cup[work[i][0]]; b = st.cup[work[i][1]]; t = (a <= v[work[i][1]] - b) ? a : v[work[i][1]] - b; if(t == 0) continue; tst = st; tst.cup[work[i][0]] = a - t; tst.cup[work[i][1]] = b + t; if(isInPath(tst)) continue; search(tst); } path_count--; } int main() { ST init = {.cup[0] = 12}; search(init); printf("The best method is #%d in step %d\n", min_index, min_count - 1); return 0; }
重剑无锋,大巧不工