标签:
此题为小白书里数据结构基础的线性表训练
翻译请戳 http://luckycat.kshs.kh.edu.tw/
解题思路
开个二维数组模拟整个过程就行了。
注意题目中提到的不理会的情况。测试数据不会很刁难。
这个模拟还是挺烦的。。。
代码:
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int MAX_LEN = 25; typedef struct pos { int x, y; }npos; int nBlock; int stack[MAX_LEN][MAX_LEN]; npos found(int index) { for(int i=0; i<nBlock; i++) { for(int j=0; j<MAX_LEN; j++) if(stack[i][j] == index) { npos temp; temp.x = i; temp.y = j; return temp; } else if(stack[i][j] == -1) break; } } int count(int index) { npos now = found(index); int count = 0; for(int j=now.y+1; stack[now.x][j]>=0; j++,count++); return count; } void initPos(int index) { npos now = found(index); // int sum = count(index); for(int j=now.y+1; stack[now.x][j]>=0; j++) { int temp = stack[now.x][j]; stack[temp][0] = temp; stack[now.x][j] = -1; } } int main() { while(scanf("%d", &nBlock) == 1) { char order[20]; int a, b; memset(stack, -1, sizeof(stack)); for(int i=0; i<nBlock; i++) stack[i][0] = i; getchar(); gets(order); while(strstr(order, "quit") == NULL) { if(strstr(order, "move")!=NULL && strstr(order, "onto")!=NULL) { sscanf(order, "move %d onto %d", &a, &b); // initPos(a); initPos(b); npos temp1 = found(b); npos temp2 = found(a); if(temp1.x != temp2.x) { initPos(a);initPos(b); } if(temp1.x != temp2.x) { stack[temp1.x][temp1.y+1] = a; stack[temp2.x][temp2.y] = -1; } } if(strstr(order, "move")!=NULL && strstr(order, "over")!=NULL) { sscanf(order, "move %d over %d", &a, &b); // initPos(a); int temp = count(b); npos tempPos = found(b); npos tempa = found(a); if(tempPos.x != tempa.x) initPos(a); if(tempPos.x != tempa.x) { stack[tempPos.x][tempPos.y+temp+1] = a; stack[tempa.x][tempa.y] = -1; } } if(strstr(order, "pile")!=NULL && strstr(order, "onto")!=NULL) { sscanf(order, "pile %d onto %d", &a, &b); // initPos(b); // int temp = count(a); npos tempa = found(a); npos tempb = found(b); if(tempa.x != tempb.x) initPos(b); int i, j; for(j=tempa.y,i=tempb.y+1; tempa.x != tempb.x&&stack[tempa.x][j]>=0; j++,i++) { stack[tempb.x][i] = stack[tempa.x][j]; stack[tempa.x][j] = -1; } } if(strstr(order, "pile")!=NULL && strstr(order, "over")!=NULL) { sscanf(order, "pile %d over %d", &a, &b); int countb = count(b); // int countb = count(b); npos tempa = found(a); npos tempb = found(b); int i, j; for(j=tempa.y,i=tempb.y+countb+1; tempa.x != tempb.x && stack[tempa.x][j]>=0; j++,i++) { stack[tempb.x][i] = stack[tempa.x][j]; stack[tempa.x][j] = -1; } } gets(order); } for(int i=0; i<nBlock; i++) { int j = 0; cout << i << ":"; while(stack[i][j]>=0) { cout << " " << stack[i][j]; j++; } if(i != nBlock) cout << endl; } } return 0; }
标签:
原文地址:http://www.cnblogs.com/ZengWangli/p/5747670.html