• move a onto b where a and b are block numbers, puts block a onto block b after returning any blocks that arestacked on top of blocks a and b to their initial positions.
• move a over b where a and b are block numbers, puts block a onto the top of the stack containing block b, afterreturning any blocks that are stacked on top of block a to their initial positions.
• pile a onto b where a and b are block numbers, moves the pile of blocks consisting of block a, and any blocksthat are stacked above block a, onto block b. All blocks on top of block b are moved to theirinitial positions prior to the pile taking place. The blocks stacked above block a retain their orderwhen moved.
• pile a over b where a and b are block numbers, puts the pile of blocks consisting of block a, and any blocksthat are stacked above block a, onto the top of the stack containing block b. The blocks stackedabove block a retain their original order when moved.• quitterminates manipulations in the block world.
文字说明:
*归位的意思是i还到初始位置i处
move a onto b : a,b后面的元素都分别归位,a到b后面
move a over b : a后归位,a直接移到b所在容器后
pile a onto b : b后归位,a以及a以后的元素直接移到b后
pile a over b : 都不归位,a以及a以后的元素直接移到b所在的容器后
图解:(图是别人帮忙画的)
注意:要特判哦,如果a,b所在的容器是相同的则不用管
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int n;
vector<int> v[26];//相当于一个二维数组,列确定,每列的行不确定
void find_pile_height(int a,int &p,int &h){//找到a所在的堆以及高度
for(p=0;p<n;p++){
for(h=0;h<v[p].size();h++){
if(v[p][h]==a)return;
}
}
}
void clear_above(int p,int h){//把第p堆高度为h的以上的方块归队
for(int i=h+1;i<v[p].size();i++){
int b=v[p][i];
v[b].push_back(b);//此时的b还在p后
}
v[p].resize(h+1);//只保留0~h个元素
}
void moveOnto(int a,int b){
int pa,ha,pb,hb;
find_pile_height(a,pa,ha);
find_pile_height(b,pb,hb);
if(pa!=pb){
clear_above(pa,ha);
clear_above(pb,hb);
v[pb].push_back(a);
v[pa].resize(ha);
}
}
void moveOver(int a,int b){
int pa,ha,pb,hb;
find_pile_height(a,pa,ha);
find_pile_height(b,pb,hb);
if(pa!=pb){
clear_above(pa,ha);
v[pb].push_back(a);
v[pa].resize(ha);
}
}
void pileOnto(int a,int b){
int pa,ha,pb,hb;
find_pile_height(a,pa,ha);
find_pile_height(b,pb,hb);
if(pa!=pb){
clear_above(pb,hb);
for(int i=ha;i<v[pa].size();i++){
v[pb].push_back(v[pa][i]);
}
v[pa].resize(ha);
}
}
void pileOver(int a,int b){
int pa,ha,pb,hb;
find_pile_height(a,pa,ha);
find_pile_height(b,pb,hb);
if(pa!=pb){
for(int i=ha;i<v[pa].size();i++){
v[pb].push_back(v[pa][i]);
}
v[pa].resize(ha);
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
v[i].push_back(i);
}
int a,b;
string str1,str2;
cin>>str1;
while(str1!="quit"){
cin>>a>>str2>>b;
if(str1=="move"&&str2=="onto")moveOnto(a,b);
if(str1=="move"&&str2=="over")moveOver(a,b);
if(str1=="pile"&&str2=="onto")pileOnto(a,b);
if(str1=="pile"&&str2=="over")pileOver(a,b);
cin>>str1;
}
for(int i=0;i<n;i++){
cout<<i<<":";
for(int j=0;j<v[i].size();j++){
cout<<" "<<v[i][j];
}
cout<<endl;
}
return 0;
}