题目大意:
有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;
}