帮我写一个程序使用c语言不能使用c++语言。输入整数 n 表示有编号为 1到n 的木块分别放在顺序排列编号为 1~n 的位置。 设 x 和 y 是木块块号。现对这些木块进行操作操作指令有如下四种: mov x to y :把 x 、 y 上的木块放回各自原来的位置再把 木块x 放到木块 y 上; mov x on y :把 x 上的木块放回各自的原来的位置再把 x 放到包含了 y 的木块堆上;
#include <stdio.h> #include <string.h>
int n; int pos[55][55]; // pos[i][j]表示第i个位置上j的上方有哪些块 int top[55]; // top[i]表示第i个位置上最上面块的编号
// 将块b及其上方的块从位置p移动到位置q void move(int b, int p, int q) { int i; for (i = 0; pos[p][b] != -1; i++) { int t = pos[p][b]; pos[p][b] = pos[q][top[q]]; top[q] = t; b = t; } pos[p][b] = -1; pos[q][top[q]] = b; top[q] = b; }
int main() { int i, j; char cmd[10]; memset(pos, -1, sizeof(pos)); // 初始时每个位置没有块 for (i = 1; i <= 50; i++) { top[i] = i; // 初始时每个位置最上面的块就是它本身 } scanf("%d", &n); while (scanf("%s", cmd) == 1 && strcmp(cmd, "quit") != 0) { int a, b; char on[5]; scanf("%d %s %d", &a, on, &b); if (a == b || top[a] == top[b]) continue; // 非法指令 if (cmd[0] == 'm') { // mov if (on[1] == 'n') { // mov x to y move(a, top[a], b); } else { // mov x on y move(a, top[a], top[b]); } } else { // shift int p, q; for (i = 1; i <= n; i++) { if (pos[i][a] != -1) { p = i; } if (pos[i][b] != -1) { q = i; } } if (on[1] == 'n') { // shift x to y move(a, p, q); } else { // shift x on y move(a, p, top[b]); } } } for (i = 1; i <= n; i++) { printf("%d:", i); for (j = 1; pos[i][j] != -1; j++) { printf(" %d", pos[i][j]); } printf("\n"); } return 0;
原文地址: https://www.cveoy.top/t/topic/eDCS 著作权归作者所有。请勿转载和采集!