#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30
struct node{
int k;
struct node* next;
};
struct node* li[MAX];
struct node block[MAX];
/* move block to their initial position
from p to all the top*/
void toIni(struct node* p){
while(p!=NULL){
struct node* te = p;
int key = p->k;
li[key]->next = p;
p = te->next;
te->next = NULL;
}
}
/* move block a to block b , b's postions*/
void move(struct node* a, struct node* b){
b->next = a;
}
/* return int from char* */
int val(char* s){
int k = strlen(s);
int res = 0;
int i;
for(i=0; i<k;i++){
res = res*10+(s[i]-'0');
}
return res;
}
/* search the block b's father */
struct node* search(int key){
int i;
for(i=0; i<MAX;i++){
struct node* p = li[i];
while(p->next != NULL){
if(p->next->k == key){
return p;
}
p = p->next;
}
}
return NULL;
}
/*judge whether they are in the same pack */
int judge(struct node* a, struct node* b){
struct node* te = a;
struct node* em = b;
int res = -1;
while(te->next != NULL){
if(te->next == b){
res = 1;
break;
}
te = te->next;
}
while(em->next != NULL){
if(em->next == a){
res = 1;
break;
}
em = em->next;
}
return res;
}
void show(int n){
int i=0;
for(;i<n; i++){
printf("%d:",i);
struct node* p = li[i] -> next;
while(p != NULL){
printf(" %d", p->k);
p = p->next;
}
printf("\n");
}
}
/* move a onto b */
void moveTo(char* a, char* b, char* c, char* d){
int bv = val(b);
int dv = val(d);
if(bv == dv) return ;
struct node* bp = search(bv);
struct node* dp = search(dv);
if(judge(bp->next, dp->next)== 1) return;
if(strcmp(a, "move") == 0){
if(strcmp(c, "onto") == 0){
toIni(bp->next->next);
toIni(dp->next->next);
struct node* bq = bp->next;
struct node* dq = dp->next;
dq->next = bq;
bq->next = NULL;
bp->next = NULL;
}
else if(strcmp(c, "over") == 0){
toIni(bp->next->next);
struct node* bf = bp->next;
while(dp->next != NULL){
dp = dp->next;
}
dp->next = bf;
bf->next = NULL;
bp->next = NULL;
}
}
else if(strcmp(a, "pile") == 0){
if(strcmp(c, "onto") == 0){
toIni(dp->next->next);
dp->next->next = bp->next;
bp->next = NULL;
}
else if(strcmp(c, "over") == 0){
while(dp->next != NULL){
dp = dp->next;
}
dp->next = bp->next;
bp->next = NULL;
}
}
}
int main(void){
char cmd[14] = {0};
char tye[5]={'\0'};
char tke[5]={'\0'};
char *p[5];
int i,n;
while(scanf("%d", &n)!=EOF && n>0){
getchar();
for(i=0; i<MAX;i++){
block[i].next = NULL;
block[i].k = i;
li[i] = (struct node*)malloc(sizeof(struct node));
li[i]->next = &(block[i]);
li[i]->k = -1;
}
while(gets(cmd) && strcmp(cmd, "quit")!=0 ){
int t = 0;
p[0] = strtok(cmd, " ");
while(p[t]){
p[++t] = strtok(NULL, " ");
}
moveTo(p[0], p[1], p[2], p[3]);
}
show(n);
memset(li, 0, sizeof li);
memset(block, 0, sizeof block);
}
return 0;
}
UVAOJ 101 移动木块
最新推荐文章于 2019-02-08 21:07:13 发布