Untitled
unknown
c_cpp
2 years ago
2.6 kB
2
Indexable
Never
#include <stdio.h> #include <stdlib.h> #include <string.h> char command1[5], command2[5]; int table[50][50]; int pos[50], len[50];//pos存每一本書所在的table, len存每個table的長度 void printTable(int n){ for(int i = 0; i < n; i++){ printf("%d:", i); for(int j = 0; j < len[i]; j++){ if(table[i][j] != -1) printf(" %d", table[i][j]); } printf("\n"); } } void init(int n){ memset(table, -1, sizeof(table)); //把table每一格設成-1 for(int i = 0; i < n; i++){ len[i] = 1; table[i][0] = i; pos[i] = i; } } void push(int a, int b){ table[pos[b]][len[pos[b]]] = a; //在b所在的table的最後一格把a塞進去 pos[a] = pos[b]; } void reset(int a){ //把書放回原本的table int flag = 0, index = 0, length = len[pos[a]]; for(int i = 0; i < length; i++){ if(table[ pos[a] ][i] == a){ flag = 1; index = i; } else if(flag == 1){ int num = table[pos[a]][i]; table[num][len[num]] = num; pos[num] = num; table[pos[a]][i] = -1; len[pos[a]]--; len[num]++; } } len[pos[a]] = index+1; } void pileOver(int a, int b){ int i = 0, flag = 0, length = len[pos[a]], cur_pos = pos[a]; //cur_pos -> 存a現在的table, length存cur_pos的長度 for(i = 0; i < length; i++){ if(table[pos[a]][i] == a) flag = 1; if(flag == 1){ int num = table[cur_pos][i]; //printf("num%d = %d\n",i, num); len[cur_pos]--; table[cur_pos][i] = -1; pos[num] = pos[b]; table[pos[b]][len[pos[b]]] = num; len[pos[b]]++; } } } int main(){ int n, a, b; scanf("%d", &n); init(n); while(scanf("%s", command1)){ if(strcmp(command1, "exit") == 0) break; scanf("%d %s %d", &a, command2, &b); if(pos[a] == pos[b]) continue; if(command1[0] == 'm'){ if(strcmp(command2, "onto") == 0){ reset(a); reset(b); } else reset(a); len[pos[a]]--; push(a, b); len[pos[b]]++; } else{ if(strcmp(command2, "onto") == 0){ reset(b); pileOver(a, b); } else pileOver(a, b); } //printTable(n); } printTable(n); }