UVa 442 - Matrix Chain Multiplication
這個禮拜上課時提到了 Stack
找了一題 UVa 的題目
透過 C 使用 Linked List 實作 Stack
Uva 442 Matrix Chain Multiplication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
|
#include<stdio.h> #include<stdlib.h> #include<string.h>
struct m{ char name; int row; int col; }; typedef struct m Matrix;
struct s{ Matrix matrix; struct s* downPtr; }; typedef struct s Stack;
int isEmpty(Stack **stack){ if(stack == NULL) return 1; else return 0; }
void push(Stack **stack,Matrix matrix){ Stack * new_stack = (Stack*) malloc(sizeof(Stack)); if(new_stack!=NULL){ new_stack->matrix = matrix; new_stack->downPtr = (*stack); (*stack) = new_stack; } }
Matrix pop(Stack **stack){ Stack *top = *stack; Matrix matrix = top->matrix; *stack = (*stack)-> downPtr; free(top); return matrix; };
void show(Stack **stack){ Stack *now = *stack; while(now!=NULL){ Matrix matrix = now->matrix; printf("%c %d %d -> ",matrix.name,matrix.row,matrix.col); now = now->downPtr; } printf("NULL\n"); }
int main(){ int num; scanf("%d\n",&num); Matrix matrix[30];
for(int i=0;i<num;i++){ char name; int row,col; scanf("%c%d%d\n",&name,&row,&col); matrix[i].name = name; matrix[i].row = row; matrix[i].col = col; }
char command[10000]={0}; while(scanf("%s",command)!=EOF){ int ans=0; int flag=1; Stack* stack = NULL;
int len = strlen(command); for(int i=0;i<len;i++){ if(command[i]=='(') continue; else if(command[i]==')'){ Matrix m1,m2; if(isEmpty(&stack)){ flag=0; break; }else{ m2 = pop(&stack); } if(isEmpty(&stack)){ flag=0; break; }else{ m1 = pop(&stack); } if(m1.col!=m2.row){ flag=0; break; } ans += m1.row*m1.col*m2.col; m1.col = m2.col; push(&stack,m1); }else{ int j=0; for(j=0;j<num;j++) if(command[i]==matrix[j].name) break; push(&stack,matrix[j]); } } if(flag) printf("%d\n",ans); else printf("error\n");
memset(command,0,sizeof(command)/sizeof(char)); }
return 0; }
|