This is (supposed to be) a soln for a ACM problem
But the program produces a runtime error.
Can anyone spot the bug?
#include<iostream>
#include<string>
#define MAX 25
using namespace std;
void print_blocks();
int return_initial(int a);//return all the blocks
//on top of block a to their initial pos
int track[MAX];//in which stack a block is currently stacked
int blkpos[MAX][MAX];//block stacks
int n;
int main()
{
//Initialize Start
cin>>n;
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
blkpos[i][j] = -1;
for(int i = 0; i < n; ++i)
blkpos[i][0] = i;
for(int i = 0; i < n; ++i)
track[i] = i;
//Initialize End
string command;
int a,b;
while(cin>>command)
{
if(command == "quit")
break;
if(command == "move")
{
cin>>a>>command>>b;
if(track[a] == track[b])//Illegal command
continue;
if(command == "onto")//command == move a onto b
{
int pos = return_initial(a);
blkpos[track[b]][ return_initial(b) + 1] = a;
blkpos[track[a]][pos] = -1;
track[a] = track[b];
}
else//command == move a over b
{
int pos = return_initial(a);
int i;
for( i = 0; blkpos[track[b]][i] != -1; ++i)
;
blkpos[track[b]][i] = a;
blkpos[track[a]][pos] = -1;
track[a] = track[b];
}
}
else //command == pile
{
cin>>a>>command>>b;
if(track[a] == track[b])
continue;
if(command == "onto") // command == pile a onto b
{
int pos = return_initial(b);
int i;
for( i = 0; blkpos[track[a]][i] != a; ++i)
;
int from = track[a];
for( ; blkpos[from][i] != -1; ++i)
{
blkpos[track[b]][++pos] = blkpos[from][i];
track[blkpos[from][i]] = track[b];
blkpos[from][i] = -1;
}
}
else //command == pile a over b
{
int pos;
int i;
for(i = 0; blkpos[track[b]][i] != b; ++i)
;
pos = i;
for( i = 0; blkpos[track[a]][i] != a; ++i)
;
int from = track[a];
for( ; blkpos[from][i] != -1; ++i)
{
blkpos[track[b]][++pos] = blkpos[from][i];
track[blkpos[from][i]] = track[b];
blkpos[from][i] = -1;
}
}
}
}
print_blocks();
}
int return_initial(int a)
{
int i;
for(i = 0; blkpos[ track[a]][i] != a; ++i )
;
int temp;
int pos = i;
for(++i ; (temp = blkpos[ track[a]][i]) != -1; ++i )
{
blkpos[ track[a]][i] = -1;
int j;
for( j = 0; blkpos[temp][j] != -1; ++j)
;
blkpos[temp][j] = temp;
track[temp] = temp;
}
return pos;
}
void print_blocks()
{
for(int i = 0; i < n; ++i)
{
cout<<i<<":";
for(int j = 0; blkpos[i][j] != -1; ++j)
{
cout<<" "<<blkpos[i][j];
}
cout<<"\n";
}
}