101 - The Blocks Problem

参考博客: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值