uva 101(线性表)

来源:互联网 发布:傲飞数据整合平台下载 编辑:程序博客网 时间:2024/05/16 10:40

题解:用栈的数组存木块,然后设置一个数组储存每个木块当前所在的位置,每次移动都要更新,注意不要把位置的储存成了值,另外,如果a和b木块在同一个位置就不需要移动。

例如:

sample input

2

move 0 over 1

move 1 over 0

quit

输出结果是

0:

1: 1 0

#include <cstdio>#include <cstring>#include <stack>using namespace std;const int N = 30;stack<int> s[N];int flag[N];void init (int pl, int bl) {while (s[pl].top() != bl) {int temp = s[pl].top();flag[temp] = temp;s[temp].push(temp);s[pl].pop();}return;}void change (int bl1, int bl2) {stack<int> temp;int flag1 = flag[bl1];while (s[flag1].top() != bl1) {temp.push(s[flag1].top());s[flag1].pop();}temp.push(s[flag1].top());s[flag1].pop();int flag2 = flag[bl2];while (!temp.empty()) {s[flag2].push(temp.top());flag[temp.top()] = flag2;temp.pop();}}int main() {int n, bl1, bl2;char keyw1[N], keyw2[N];scanf("%d", &n);for (int i = 0; i < n; i++) {s[i].push(i);flag[i] = i;}getchar();while (1) {scanf("%s", keyw1);if (keyw1[0] == 'q')break;scanf("%d%s%d", &bl1, keyw2, &bl2);if (keyw1[0] == 'm') {if (keyw2[1] == 'n' && flag[bl1] != flag[bl2]) {int temp2 = flag[bl2];init(temp2, bl2);int temp1 = flag[bl1];init(temp1, bl1);s[temp2].push(bl1);s[temp1].pop();flag[bl1] = temp2;}else if (flag[bl1] != flag[bl2]){int temp1 = flag[bl1];init(temp1, bl1);int temp2 = flag[bl2];s[temp2].push(bl1);s[temp1].pop();flag[bl1] = temp2;}}else {if (keyw2[1] == 'n' && flag[bl1] != flag[bl2]) {int temp2 = flag[bl2];init(temp2, bl2);change(bl1, bl2);}else {if (flag[bl1] != bl2)change(bl1, bl2);}}}for (int i = 0; i < n; i++) {printf("%d:", i);if (!s[i].empty()) {stack<int> temp;while (!s[i].empty()) {temp.push(s[i].top());s[i].pop();}while (!temp.empty()) {printf(" %d", temp.top());temp.pop();}printf("\n");}elseprintf("\n");}return 0;}


0 0