Uva 101 the block problem 木块问题
题目大意:
输入n,得到编号为0n-1的木块,分别摆放在顺序排列编号为0n-1的位置。现对这些木块进行操作,操作分为四种。
1、move a onto b:把木块a、b上的木块放回各自的原位,再把a放到b上;
2、move a over b:把a上的木块放回各自的原位,再把a发到含b的堆上;
3、pile a onto b:把b上的木块放回各自的原位,再把a连同a上的木块移到b上;
4、pile a over b:把a连同a上木块移到含b的堆上。
当输入quit时,结束操作并输出0~n-1的位置上的木块情况
Sample Input
10
move 9 onto 1
move 8 over 1
move 7 over 1
move 6 over 1
pile 8 over 6
pile 8 over 5
move 2 over 1
move 4 over 9
quit
Sample Output
0: 0
1: 1 9 2 4
2:
3: 3
4:
5: 5 8 7 6
6:
7:
8:
9:
#include<cstdio>
#include<string>
#include<vector>
#include<iostream>
using namespace std;
const int maxn = 30;
int n;//大理石的数量
vector<int>pile[maxn];//每个pile[i]都是一个vector,相当于一个二维数组,一维的维度是确定的maxn,二维是不确定的
//找木块a所在的pile和height,以引用的方式返回调用者(p,h)
void find_block(int a,int& p,int& h)
{
for(p=0 ; p<n ; p++)
{
for(h=0 ; h<pile[p].size() ; h++)
{
if(pile[p][h]==a) return;
}
}
}
//把第p堆高度位h的木块上方的所有木块移回原位
void clear_above(int p,int h)
{
for(int i=h+1 ; i<pile[p].size() ; i++)
{
int b=pile[p][i];
pile[b].push_back(b);//将木块b放回原来位置
}
pile[p].resize(h+1);//pile对应的下标是0—h,所以应该加一
}
//把第p堆高度位h的木块整体移动到p2堆的顶部
void pile_onto(int p,int h,int p2)
{
for(int i=h ; i<pile[h].size() ; i++)
{
pile[p2].push_back(pile[p][i]);
}
pile[p].resize(h);
}
//打印
void print()
{
for(int i=0 ; i<n ; i++)
{
printf("%d:",i);
for(int j=0 ; j<pile[i].size() ; j++) printf(" %d",pile[i][j]);
printf("\n");
}
}
int main()
{
int a,b;
cin>>n;//输入大理石的数量
string s1,s2;//s1=move/pile,s2=onto/over
for(int i=0 ; i<n ; i++) pile[i].push_back(i);//把木块放到对应的坑里
while(cin>>s1>>a>>s2>>b)//e.g. move a onto b
{
int pa,pb,ha,hb;//分别用来存a,b在哪一堆,多高
find_block(a,pa,ha);
find_block(b,pb,hb);
if(pa==pb) continue;//非法指令(a,b在同一堆)
if(s2=="onto") clear_above(pb,hb);//指令是onto则先将b上的木头归位
if(s1=="move") clear_above(pa,ha);//指令是move再将a上的木头归位
pile_onto(pa,ha,pb);
}
print();
return 0;
}