很烦人的一道模拟(似乎所有的模拟都这样~~~),用block[][]来记录各个block列的状态,b_n[]保存各个列的高度,b_ind[]用于查找第i个block所在的列,a_h,b_h是a·b其在block列的高度,a_p,b_p是a,b所在的列数。写完代码一交WA,改了20多分钟,才发现漏了++b_n[b_p]~~~~做题要细心,写代码更要细心!
#include <iostream>
#include <cstdio>
#include <memory>
#include <algorithm>
using namespace std;
#define MAXN 100
int block[MAXN][MAXN],b_ind[MAXN],b_n[MAXN];
int n,a_p,b_p,a_h,b_h,tmp;
int init()
{
int i,j;
for(i = 0;i <= n; ++i)
{
block[i][0] = i;
b_ind[i] = i;
b_n[i] = 1;
}
return 0;
}
int move_onto(const int& a,const int& b)
{
int i,j;
for(i = a_h+1;i < b_n[a_p]; ++i)
{
block[block[a_p][i]][0] = block[a_p][i];
b_n[block[a_p][i]] = 1;
b_ind[block[a_p][i]] = block[a_p][i];
}
b_n[a_p] = a_h;
for(i = b_h+1;i < b_n[b_p]; ++i)
{
block[block[b_p][i]][0] = block[b_p][i];
b_n[block[b_p][i]] = 1;
b_ind[block[b_p][i]] = block[b_p][i];
}
b_n[b_p] = b_h+2;
b_ind[a] = b_p;
block[b_p][b_h+1] = a;
return 0;
}
int move_over(const int& a,const int& b)
{
int i,j;
for(i = a_h+1;i < b_n[a_p]; ++i)
{
block[block[a_p][i]][0] = block[a_p][i];
b_n[block[a_p][i]] = 1;
b_ind[block[a_p][i]] = block[a_p][i];
}
b_n[a_p] = a_h;
b_ind[a] = b_p;
block[b_p][b_n[b_p]] = a;
++b_n[b_p];
return 0;
}
int pile_onto(const int& a,const int& b)
{
int i,j;
for(i = b_h+1;i < b_n[b_p]; ++i)
{
block[block[b_p][i]][0] = block[b_p][i];
b_n[block[b_p][i]] = 1;
b_ind[block[b_p][i]] = block[b_p][i];
}
b_n[b_p] = b_h+1;
for(i = a_h; i < b_n[a_p]; ++i)
{
block[b_p][b_n[b_p]] = block[a_p][i];
b_ind[block[a_p][i]] = b_p;
++b_n[b_p];
}
b_n[a_p] = a_h;
return 0;
}
int pile_over(const int& a,const int& b)
{
int i,j;
for(i = a_h;i < b_n[a_p]; ++i)
{
block[b_p][b_n[b_p]] = block[a_p][i];
++b_n[b_p];
b_ind[block[a_p][i]] = b_p;
}
b_n[a_p] = a_h;
return 0;
}
int main()
{
int i,j,a,b;
char s1[10],s2[10];
char s_move[]="move",s_pile[]="pile",s_onto[]="onto",s_over[]="over";
char s_quit[] = "quit";
while(scanf("%d",&n) != EOF)
{
init();
while(true)
{
scanf("%s",s1);
if(!strcmp(s1,s_quit))
break;
scanf("%d%s%d",&a,s2,&b);
a_p = b_ind[a];
b_p = b_ind[b];
if(a_p==b_p)
continue;
a_h = b_h = 0;
j = 0;
while(1)
{
if(block[a_p][j] == a)
break;
++j;
}
a_h = j;
j = 0;
while(1)
{
if(block[b_p][j] == b)
break;
++j;
}
b_h = j;
if(!strcmp(s1,s_move))
{
if(!strcmp(s2,s_onto))
move_onto(a,b);
else
move_over(a,b);
}else
{
if(!strcmp(s2,s_onto))
pile_onto(a,b);
else
pile_over(a,b);
}
}
for(i = 0;i < n; ++i)
{
cout<<i<<":";
for(j = 0;j < b_n[i]; ++j)
cout<<' '<<block[i][j];
cout<<endl;
}
}
return 0;
}