题意:有n(0<n<25)快block,有5种操作:
move a onto b 在将a搬到b上之前,先把a和b上的积木放回原來的位置
move a over b在将a搬到b所在的那堆积木上前,先把a上的积木放回原來的位罝
pile a onto b 将包括a本身和上方的积木一起放到b上,在放之前b上方的积木放回原来的位置
pile a over b 将包括a本身和上放的积木一起搬到到b所在的那堆上
quit结束命令,前四个动作中若ab在同一堆中,则不做改变。
Sure原创,转载请注明出处。
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
const int maxn = 30;
int stack[maxn][maxn],num[maxn],belong[maxn];
char cao[maxn],wei[maxn];
int n;
void break_up(int pos,int val)
{
while(stack[pos][num[pos]-1] != val)
{
int st = stack[pos][--num[pos]];
stack[st][num[st]++] = st;
belong[st] = st;
}
return;
}
void put(int fr,int val,int to)
{
int p = 0;
while(stack[fr][p] != val) p++;
int bj = p;
while(p < num[fr])
{
stack[to][num[to]++] = stack[fr][p];
belong[stack[fr][p++]] = to;
}
num[fr] = bj;
return;
}
void solve()
{
for(int i=0;i<n;i++)
{
num[i] = 1;
belong[i] = i;
stack[i][0] = i;
}
int u,v;
while(scanf("%s",cao))
{
if(strcmp(cao , "quit") == 0) break;
scanf("%d %s %d",&u,wei,&v);
int x = belong[u];
int y = belong[v];
if(x == y) continue;
if(strcmp(cao , "move") == 0)
{
if(strcmp(wei , "onto") == 0)
{
break_up(x , u);
break_up(y , v);
stack[y][num[y]++] = stack[x][--num[x]];
belong[u] = y;
}
else
{
break_up(x , u);
stack[y][num[y]++] = stack[x][--num[x]];
belong[u] = y;
}
}
else
{
if(strcmp(wei , "onto") == 0)
{
break_up(y , v);
put(x , u , y);
}
else
{
put(x , u , y);
}
}
}
return;
}
void out()
{
for(int i=0;i<n;i++)
{
printf("%d:",i);
for(int j=0;j<num[i];j++)
{
printf(" %d",stack[i][j]);
}
puts("");
}
return;
}
int main()
{
while(~scanf("%d",&n))
{
solve();
out();
}
return 0;
}