101 - The Blocks Problem

#include <iostream>
#include <cstdio>
#include <sstream>
#include <string>
using namespace std;

const int Max=30;
struct node
{
	int stack[Max];
	int top;//+1
	node():top(0){}
}s[Max];

int n;

void init()
{
	for(int i=0;i<n;i++)
		s[i].stack[s[i].top++]=i;
}
int getCommand(string &s1,string &s2)
{
	if(s1=="move" && s2=="onto")
		return 1;
	else if(s1=="move" && s2=="over")
		return 2;
	else if(s1=="pile" && s2=="onto")
		return 3;
	else if(s1=="pile" && s2=="over")
		return 4;
	return 0;
}
int getPos(int x,int &pos,int &lev)
{
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<s[i].top;j++)
			if(s[i].stack[j]==x)
			{
				pos=i;
				lev=j;
				return 1;
			}
	}
	return 0;
}
void handle(string &s1,int a,string &s2,int b)
{
	int sort=getCommand(s1,s2);
	int a_pos,b_pos;
	int a_lev,b_lev;
	int i;
	int temp;
	getPos(a,a_pos,a_lev);
	getPos(b,b_pos,b_lev);
	if(a_pos==b_pos)
		return ;
	switch(sort)
	{
	case 1:
		for(i=a_lev+1;i<s[a_pos].top;i++)
		{
			temp=s[a_pos].stack[i];
			s[temp].stack[s[temp].top++]=temp;
		}
		s[a_pos].top=a_lev+1;
		for(i=b_lev+1;i<s[b_pos].top;i++)
		{
			temp=s[b_pos].stack[i];
			s[temp].stack[s[temp].top++]=temp;
		}
		s[b_pos].top=b_lev+1;
		s[b_pos].stack[s[b_pos].top++]=s[a_pos].stack[--s[a_pos].top];
		break;
	case 2:
		for(i=a_lev+1;i<s[a_pos].top;i++)
		{
			temp=s[a_pos].stack[i];
			s[temp].stack[s[temp].top++]=temp;
		}
		s[a_pos].top=a_lev+1;
		s[b_pos].stack[s[b_pos].top++]=s[a_pos].stack[--s[a_pos].top];
		break;
	case 3:
		for(i=b_lev+1;i<s[b_pos].top;i++)
		{
			temp=s[b_pos].stack[i];
			s[temp].stack[s[temp].top++]=temp;
		}
		s[b_pos].top=b_lev+1;
		for(i=a_lev;i<s[a_pos].top;i++)
		{
			temp=s[a_pos].stack[i];
			s[b_pos].stack[s[b_pos].top++]=temp;
		}
		s[a_pos].top=a_lev;
		break;
	case 4:
		for(i=a_lev;i<s[a_pos].top;i++)
		{
			temp=s[a_pos].stack[i];
			s[b_pos].stack[s[b_pos].top++]=temp;
		}
		s[a_pos].top=a_lev;
		break;
	default:
		break;
	}
}

int main()
{
	/*
	freopen("101.in","r",stdin);
	freopen("101.out","w",stdout);
	//*/
	scanf("%d",&n);
	getchar();
	init();
	string command;
	while(getline(cin,command) && command!="quit")
	{
		int a,b;
		string s1,s2;
		istringstream in(command);
		in>>s1;
		in>>a;
		in>>s2;
		in>>b;
		handle(s1,a,s2,b);
	}
	for(int i=0;i<n;i++)
	{
		printf("%d:",i);
		for(int u=0;u<s[i].top;u++)
			printf(" %d",s[i].stack[u]);
		//if(s[i].top>0)
			//printf("%d",s[i].stack[s[i].top-1]);
		printf("\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值