101 - The Blocks Problem

来源:互联网 发布:云视通网络设置方法 编辑:程序博客网 时间:2024/05/15 07:07

参考博客:http://blog.csdn.net/mobius_strip/article/details/12765319



题目大意:

给你n个数字0~n-1

初始,数字i在位置i上

有如下四种操作:

move a onto b:把a、b上面的所有数字移动回原来的位置,再把a移动到b上

move a  over b:  把a上的数字移动回数字原来的位置,再把a移动到含有b的堆的上方

pile a onto b:    把b上的数字移动回原来的位置,把含有a的堆移动到b上(a原本上面的数字顺序不变)

pile a over b:   把含有a的堆移动到含有b的堆上


思路:

提取出两种操作:

1.把堆x上面的数字移动回原来的位置       

2.把含有x的堆从x开始移动到含有y的堆上


注意特殊情况:a和b在同一个堆中的时候怎么处理

这个时候任何一条指令应该都是无效的


代码如下:

#include <iostream>#include<stdio.h>using namespace std;int stack[100][100];int place[100];int top[100];void Init_a(int a){int id = place[a];while (stack[id][top[id]] != a){int id2 = stack[id][top[id]--];place[id2] = id2;stack[id2][++top[id2]] = id2;}}void place_a_to_b(int a, int b){int temp[100], topt = -1;int id = place[a];while (stack[id][top[id]] != a){temp[++topt] = stack[id][top[id]--];}int ID = place[b];stack[ID][++top[ID]] = a;top[id]--;place[a] = ID;while (topt >= 0){place[temp[topt]] = ID;stack[ID][++top[ID]] = temp[topt--];}}int main(){FILE*stream;freopen_s(&stream, "C:\\Data\\101.txt", "r", stdin);int n;while (cin >> n){for (int i = 0; i<n; i++){stack[i][0] = i;place[i] = i;top[i] = 0;}char oper[5], type[5];int a, b;while (cin >> oper&&oper[0] != 'q'){    cin >> a >> type >> b; if (place[a] == place[b])continue;if (oper[1] == 'm')Init_a(a);if (type[2] == 'n')Init_a(b);place_a_to_b(a, b);}for (int i = 0; i < n; i++){cout << i << ": ";for (int j = 0; j <= top[i]; j++)cout << stack[i][j] << " ";cout << endl;}}return 0;}


0 0
原创粉丝点击