UVa 101 - The Blocks Problem

题目大意:

有n个木块,对木块进行如下操作:

1、move a onto b

上述的a和b都是板子的标号。将板子a放到b上面,且将a和b板子上的所有的板子都放回他们的初始位置。

2、move a over b

上述的a和b都是板子的标号。将板子a放到b板子所在堆的最上面,且将板子a上的所以板子都放回他们的初始位置。

3、pile a onto b

上述的a和b都是板子的标号。将板子a及a上的所有板子都放到b上,且将板子b上的所有板子都放回他们的初始位置。

4、pile a over b

上述的a和b都是板子的标号。将板子a及a上的所有板子都放到b板子所在堆的最上面。

 注意如果要移动的a和b在统一堆上,就放弃操作。

 

#include<cstdio>
#include<cstring>
#include<cstdlib>

typedef struct
{
	int a[30];
	int top;
}stack;

int n, from, to;
char s[5], e[5];
stack b[30];
int x, y;   //记录要移动的木块在哪一堆
int p, p1, p2;  //记录要移动的木块在某一堆的位置

int find(int num)
{
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < b[i].top; j++)
		{
			if(num == b[i].a[j])
			{
				p = j;
				return i;
			}
		}
	}
}

void judge(char *s,char *e)
{
	if((strcmp(s,"move") == 0) && (strcmp(e,"onto") == 0))
	{
		while(p1 < b[x].top-1)        //判断from上是否有其他木块,如果有将其放回初始位置
		{
			int t = b[x].a[b[x].top-1];
			b[t].a[b[t].top++] = t;
			b[x].top--;
		}
		while(p2 < b[y].top-1)      //判断to上是否有其他木块,如果有将其放回初始位置
		{
			int t = b[y].a[b[y].top-1];
			b[t].a[b[t].top++] = t;
			b[y].top--;
		}
		b[y].a[b[y].top++] = b[x].a[b[x].top-1];   //移动木块
		b[x].top--;
	}
	if((strcmp(s,"move") == 0) && (strcmp(e,"over") == 0))
	{
		while(p1 < b[x].top-1)        //判断from上是否有其他木块,如果有将其放回初始位置
		{
			int t = b[x].a[b[x].top-1];
			b[t].a[b[t].top++] = t;
			b[x].top--;
		}
		b[y].a[b[y].top++] = b[x].a[b[x].top-1];
		b[x].top--;
	}
	if((strcmp(s,"pile") == 0) && (strcmp(e,"onto") == 0))
	{
		while(p2 < b[y].top-1)      //判断to上是否有其他木块,如果有将其放回初始位置
		{
			int t = b[y].a[b[y].top-1];
			b[t].a[b[t].top++] = t;
			b[y].top--;
		}
		int count = 0;
		for(int j = p1; j < b[x].top; j++)
		{
			b[y].a[b[y].top++] = b[x].a[j];
			count++;
		}
		b[x].top -= count;   //更新b[x].top
	}
	if((strcmp(s,"pile") == 0) && (strcmp(e,"over") == 0))
	{
		int count = 0;
		for(int j = p1; j < b[x].top; j++)
		{
			b[y].a[b[y].top++] = b[x].a[j];
			count++;
		}
		b[x].top -= count;
	}
}

int main()
{
//	freopen("D:\\1.txt","r",stdin);
	while(scanf("%d",&n) != EOF)
	{
		for(int i = 0; i < n; i++)
		{
			b[i].a[0] = i;
			b[i].top = 1;
		}
		while(1)
		{
			scanf("%s",s);
			if(strcmp(s,"quit") == 0)
				break;
			scanf("%d%s%d",&from,e,&to);
			x = find(from);
			p1 = p;
			y = find(to);
			p2 = p;
			if(x == y) continue;
			judge(s,e);
		}
		for(int i = 0; i < n; i++)
		{
			printf("%d:",i);
			for(int j = 0; j < b[i].top; j++)
				printf(" %d",b[i].a[j]);
			printf("\n");
		}
	}
	return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值