UVA 101 - The Blocks Problem

题目大意:输入n,代表有0到n-1个块。每个块的初始位置不变。输入指令,直到停止quit后输出移动结果。除quit指令外,针对块的移动有四种指令:1.move a onto b,将a块,b块上方的所有块扔回初始位置(不包括a块,b块)。然后将a移动到b上方;2. move a over b ,将a块上方所有块扔回初始位置,然后将a移动到b上方;3.pile a onto b,将b块上方所有块扔回初始位置,然后将a以及a上的所有块,按在a上的顺序放到b上方。4.pile a over b ,将a以及a上的所有块,按在a上的顺序放到b上方。如果要移动的两个块本就在同一列上,或两个块为同一块时,指令无效,不影响。

解题思路:题目里提到了栈堆,所以用了栈的方法(可能反而更麻烦了)。先给所有栈入栈,代表对应的块。判断指令是否有效,执行指令,quit跳出循环。移动指令需要读取将要移动块的位置(判断指令是否有效也根据这个),如果有move则a块上的所有返回初始位置,也就是出栈,回原位置入栈,如果有onto,则b块上的所有返回初始位置。剩下统一整个移动,也就是出栈,顺序倒置以后,入栈。栈的特点,后进先出。

ac代码:

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
stack <int> st[26];
void find(int m, int n, int &temp)
{
	int a[1000], len, j, code;
	for (int i=0; i<m; i++){
		len = st[i].size();
		j = 0;
		while (!st[i].empty()){
			if (st[i].top() == n)
				temp = i;
			a[j++] = st[i].top();
			st[i].pop();			
		}
		for (j--; j>=0; j--)
			 st[i].push(a[j]);
		if (temp != -1)
			break;
	} 
}
void come_back(int data, int pos)
{
	int temp;
	while(st[pos].top() != data){
		if (st[pos].empty()) 
			break;
		temp = st[pos].top();
		st[pos].pop();
		st[temp].push(temp);
		if (st[pos].empty()) 
			break;
	}
}
void gogogo(int pos1, int temp1, int pos2)
{
	int a[1000], i=0, temp2;
	do{
		temp2 = st[pos1].top();
		a[i++] = st[pos1].top();
		st[pos1].pop();
		if (st[pos1].empty()) 
			break;
	}while(temp2 != temp1);
	for (i--; i>=0; i--)
		st[pos2].push(a[i]);
}
int main()
{
	int n, len, a[26][26], size[26];
	char ins1[1005], ins2[1005];
	int temp1, temp2, pos1, pos2;
	cin >> n;
	for (int i=0; i<n; i++)
		st[i].push(i);	
	while (scanf("%s", ins1)!=EOF && strcmp(ins1, "quit")){
		scanf("%d%s%d", &temp1, ins2, &temp2);
		pos1 = pos2 = -1;
		find(n, temp1, pos1);
		find(n, temp2, pos2);
		if (temp1 == temp2 || pos1 == pos2);
		else {
			if (!strcmp(ins1, "move"))
				come_back(temp1, pos1);			
			if (!strcmp(ins2, "onto"))
				come_back(temp2	, pos2);
			gogogo(pos1, temp1, pos2);		
			find(n, temp1, pos1);
			find(n, temp2, pos2); 		
		}	
	}
	for (int i=0; i<n; i++){
		int j = 0;
		size[i] = st[i].size();
		while (!st[i].empty()){
			a[i][j++] = st[i].top();	
			st[i].pop();
		}	
	}
	for (int i=0; i<n; i++){
		printf("%d:", i);
		for (int j=size[i]-1; j>=0; j--)
			printf(" %d", a[i][j]);
		printf("\n");
	}
	
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值