題目不難,就是有點麻煩。會用到棧。
#include <stdio.h>#include <string.h>struct _r { int a[30]; int x;}r[30];int n;// 判斷a, b是否在同一堆中int pos(int a) { for (int i=0; i<n; i++) { for (int j=0; j<r[i].x; j++) { if (a == r[i].a[j]) return i; } }}int xab(int a) { for (int i=0; i<n; i++) { for (int j=0; j<r[i].x; j++) { if (a == r[i].a[j]) return j; } }}void move_onto(int a, int b, int pa, int pb) { // 下面兩個for迴圈將a, b堆上面的元素返回原來位置 for (int i=r[pa].x-1; r[pa].a[i]!=a; i--) { r[pa].x--; r[r[pa].a[i]].x++; } for (int i=r[pb].x-1; r[pb].a[i]!=b; i--) { r[pb].x--; r[r[pb].a[i]].x++; } r[pb].a[r[pb].x] = r[pa].a[r[pa].x-1]; r[pb].x++; r[pa].x--;}void move_over(int a, int b, int pa, int pb) { for (int i=r[pa].x-1; r[pa].a[i]!=a; i--) { r[pa].x--; r[r[pa].a[i]].x++; } r[pb].a[r[pb].x] = r[pa].a[r[pa].x-1]; r[pb].x++; r[pa].x--;}void pile_onto(int a, int b, int pa, int pb) { // 將b上面的元素返回原來的位置 for (int i=r[pb].x-1; r[pb].a[i]!=b; i--) { r[pb].x--; r[r[pb].a[i]].x++; } // 將a上面的元素保持到臨時棧中 int tmp_stack[30], top = 0; do { r[pa].x--; tmp_stack[++top] = r[pa].a[r[pa].x]; } while (r[pa].a[r[pa].x] != a); while (top) { r[pb].a[r[pb].x] = tmp_stack[top]; top--; r[pb].x++; }}void pile_over(int a, int b, int pa, int pb) { // 將a上面的元素保持到臨時棧中 int tmp_stack[30], top = 0; do { r[pa].x--; tmp_stack[++top] = r[pa].a[r[pa].x]; } while (r[pa].a[r[pa].x] != a); while (top) { r[pb].a[r[pb].x] = tmp_stack[top]; top--; r[pb].x++; }}void print() { for (int i=0; i<n; i++) { printf("%d:", i); for (int j=0; j<r[i].x; j++) printf(" %d", r[i].a[j]); printf("\n"); }}int main() { char str1[6], str2[6]; scanf("%d", &n); for (int i=0; i<n; i++) { r[i].x = 1; r[i].a[0] = i; } while (scanf("%s", str1)) { if (0 == strcmp(str1, "quit")) break; int a, b; scanf("%d%s%d", &a, str2, &b); int pa, pb; // a, b所在哪個堆 pa = pos(a); pb = pos(b); if (pa == pb) continue; if (0==strcmp(str1, "move") && 0==strcmp(str2, "onto")) { move_onto(a, b, pa, pb); } if (0==strcmp(str1, "move") && 0==strcmp(str2, "over")) { move_over(a, b, pa, pb); } if (0==strcmp(str1, "pile") && 0==strcmp(str2, "onto")) { pile_onto(a, b, pa, pb); } if (0==strcmp(str1, "pile") && 0==strcmp(str2, "over")) { pile_over(a, b, pa, pb); } //print(); } print(); return 0;}