# 101:The Blocks Problem

1. 把某个块上面的块放回原位；

2. 把某个块及其上的块放到另一个块所在的堆顶。

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 30;
int n,pos[maxn];
char cmd[20];
vector<int>bk[maxn];
void ret(int a,int pa){
for(int i = bk[pa].size() - 1;bk[pa][i] != a;i--){
int t = bk[pa][i];
bk[t].push_back(t);
pos[t] = t;
bk[pa].pop_back();
}
}
void put(int a,int pa,int pb){
int i = 0;
while(bk[pa][i] != a) i++;
for(int j = i;j < bk[pa].size();j++){
int t = bk[pa][j];
bk[pb].push_back(t);
pos[t] = pb;
}
for(int j = bk[pa].size() - 1;j >= i;j--) bk[pa].pop_back();
}
int main(){
scanf("%d",&n);
for(int i = 0;i < n;i++){
bk[i].push_back(i);
pos[i] = i;
}
while(fgets(cmd,15,stdin) && cmd[0] != 'q'){
int a = cmd[5] - '0',b = cmd[12] - '0';
if(a == b || pos[a] == pos[b]) continue;
if(cmd[0] == 'm') ret(a,pos[a]);
if(cmd[8] == 'n') ret(b,pos[b]);
put(a,pos[a],pos[b]);
}
for(int i = 0;i < n;i++){
printf("%d:",i);
for(int j = 0;j < bk[i].size();j++) printf(" %d",bk[i][j]);
putchar('\n');
}
return 0;
}

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 30;
int n,a,b,pos[maxn];
char cmd1[5],cmd2[5];
vector<int>bk[maxn];
void ret(int a,int pa){
for(int i = bk[pa].size() - 1;bk[pa][i] != a;i--){
int t = bk[pa][i];
bk[t].push_back(t);
pos[t] = t;
bk[pa].pop_back();
}
}
void put(int a,int pa,int pb){
int i = 0;
while(bk[pa][i] != a) i++;
for(int j = i;j < bk[pa].size();j++){
int t = bk[pa][j];
bk[pb].push_back(t);
pos[t] = pb;
}
for(int j = bk[pa].size() - 1;j >= i;j--) bk[pa].pop_back();
}
int main(){
scanf("%d",&n);
for(int i = 0;i < n;i++){
bk[i].push_back(i);
pos[i] = i;
}
while(scanf("%s%d%s%d",cmd1,&a,cmd2,&b) == 4){
if(a == b || pos[a] == pos[b]) continue;
if(cmd1[0] == 'm') ret(a,pos[a]);
if(cmd2[1] == 'n') ret(b,pos[b]);
put(a,pos[a],pos[b]);
}
for(int i = 0;i < n;i++){
printf("%d:",i);
for(int j = 0;j < bk[i].size();j++) printf(" %d",bk[i][j]);
putchar('\n');
}
return 0;
}