Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.7 kB
3
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int n, table[25][25], book[25]/*每本書的table*/, from , to, amount[25]/*每個table幾本書*/;
char oper1[8], oper2[8];
void re(int tab, int from)/*書返回原table*/, pile(int tabf, int tabt)/*搬一疊書*/;

int main(){
    scanf("%d", &n);
    
    for(int i = 0; i < n; i++){
        table[i][0] = i, book[i] = i;
        amount[i]++;
    }

    while(scanf("%s", oper1)){
        int stop = strcmp(oper1, "exit");
        if(!stop) break;

        scanf("%d %s %d", &from, oper2, &to);
        int move = strcmp(oper1, "move");
        int onto = strcmp(oper2, "onto");

        /*ft記要動的書在的table, tt記書要搬去的table*/
        int ft = book[from], tt = book[to];
        if(ft == tt) continue;
        
        /*move onto*/
        if(!move && !onto){
            re(ft, from);
            re(tt, to);
            
            /*改table上的書*/
            table[ft][amount[ft] - 1] = 0, table[tt][amount[tt]] = from;

            /*移動書後的新table*/
            book[ft] = tt;
            amount[ft]--, amount[tt]++;
        }
        /*move over*/
        else if(!move && onto != 0){
            re(ft, from);
            table[ft][amount[ft] - 1] = 0, table[tt][amount[tt]] = from;
            book[ft] = tt;
            amount[ft]--, amount[tt]++;
        }
        /*pile onto*/
        else if(move != 0 && !onto){
            re(tt, to);
            pile(ft, tt);
        }
        /*pile over*/
        else if(move != 0 && onto != 0){
            pile(ft, tt);
        }
    }
    for(int i = 0; i < n; i++){
        printf("%d:", i);
        for(int j = 0; j < amount[i]; j++) printf(" %d", table[i][j]);
        printf("\n");
    }
    return 0;
}

void re(int tab, int from){
    
    for(int i = amount[tab] - 1; table[tab][i] != from; i--){
        int num = table[tab][i];
        /*書放回原table*/
        table[tab][i] = 0, table[num][amount[num]] = num;
        /*記錄書的新table*/
        book[num] = num;
        amount[tab]--, amount[num]++;
    }

    return;
}

void pile(int tabf/*要搬的書在的table*/, int tabt/*要搬去的table*/){
    int count = 0 /*數搬了幾本書*/, ok = 0 /*判數到要搬的書了沒*/;

    for(int i = 0; i < amount[tabf]; i++){
        int num = table[tabf][i];
        if(table[tabf][i] == from) ok = 1;
        if(ok == 1){
            table[tabf][i] = 0, table[tabt][amount[tabt]] = num;
            book[num] = tabt;
            amount[tabt]++, count++;
        }
    }

    amount[tabf] -= count;
}