The question is not difficult, but a little troublesome. Stack is used.
# Include <stdio. h> # include <string. h> struct _ r {int A [30]; int X;} R [30]; int N; // judge, whether B is in the same heap 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) {// The following two for loops convert, elements on the B stack return the original position for (INT I = R [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) {// return the element above B to the original position for (INT I = R [Pb]. x-1; R [Pb]. A [I]! = B; I --) {R [Pb]. X --; R [R [Pb]. A [I]. X ++;} // keep the elements above a to the temporary stack 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) {// keep the elements above a to the temporary stack 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, b; scanf ("% d % S % d", & A, str2, & B); int Pa, PB; //, which heap of B is located? 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 ;}