Code: Select all
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define NMax 25
struct block
{
int N;
block *next, *prev;
};
// this function printing the world
void PrintWorld(block **world, int N)
{
block *cur;
int i;
for (i=0; i<N-1; ++i)
{
printf("%2d:", i);
cur = world[i];
while(cur!=NULL)
{
printf(" %d", cur->N);
cur = cur->next;
}
printf("\n");
}
// printing the last position of the world
printf("%2d:", N-1);
cur = world[N-1];
while (cur!=NULL)
{
printf(" %d", cur->N);
cur = cur->next;
}
return;
}
/*
this functions puts block Pil and all
blocks that are stacked on top of block
Pil to their initial positions
*/
void InitPil(block *pil, block **world)
{
block *cur;
if(pil->prev!=NULL)
{
pil->prev->next = NULL;
pil->prev = NULL;
world[pil->N] = pil;
}
cur = pil;
while (cur->next!=NULL)
{
cur = cur->next;
cur->prev->next = NULL;
cur->prev = NULL;
world[cur->N] = cur;
}
return;
}
int main()
{
#ifndef ONLINE_JUDGE
close(0); open("solve.in", O_RDONLY);
close(1); open("solve.out", O_WRONLY|O_CREAT|O_TRUNC, 0600);
#endif
int N, a, b, i, flag;
char comm[5], type[5];
block *world[NMax], positions[NMax], *cur;
scanf("%d", &N);
for (i=0; i<N; ++i)
{
positions[i].N = i;
positions[i].prev = positions[i].next = NULL;
world[i] = positions+i;
}
while (scanf("%s %d %s %d", comm, &a, type, &b)==4)
{
if (!strcmp(comm, "quit")) break;
/* checking the accuracy of input command */
flag = 0;
cur = &positions[a];
while ((cur->next!=NULL)&&(flag==0))
{
cur = cur->next;
if (cur->N==b) flag = 1;
}
cur = &positions[b];
while ((cur->next!=NULL)&&(flag==0))
{
cur = cur->next;
if (cur->N==a) flag = 1;
}
if ((!flag)&&(a!=b)&&(a<N)&&(b<N))
{
/* parsing command */
if (!strcmp(comm, "move"))
if (!strcmp(type, "onto"))
{
InitPil(&positions[a], world);
if (positions[b].next!=NULL) InitPil(positions[b].next, world);
positions[b].next = &positions[a];
positions[a].prev = &positions[b];
world[a] = NULL;
}
else /* then it is "move a over b" */
{
InitPil(&positions[a], world);
cur = &positions[b];
while(cur->next!=NULL) cur = cur->next;
cur->next = &positions[a];
positions[a].prev = cur;
world[a] = NULL;
}
else /* then it is "pile a .... b */
if (!strcmp(type, "onto"))
{
if (positions[b].next!=NULL) InitPil(positions[b].next, world);
positions[b].next = &positions[a];
if(positions[a].prev==NULL) world[a] = NULL;
else positions[a].prev->next = NULL;
positions[a].prev = &positions[b];
}
else /* then it is "pile a over b" */
{
cur = &positions[b];
while (cur->next!=NULL) cur = cur->next;
cur->next = &positions[a];
if(positions[a].prev==NULL) world[a] = NULL;
else positions[a].prev->next = NULL;
positions[a].prev = cur;
}
}
}
// printing the world
PrintWorld(world, N);
return 0;
}