抱歉,您的瀏覽器無法訪問本站
本頁面需要瀏覽器支持(啟用)JavaScript
了解詳情 >

這個禮拜上課時提到了 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
/*****************************************
Filename:p442.c
Author:Willy Chen(willychen.org)
Date:2018.04.19
*****************************************/
#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;

// Check if the stack is empty
int isEmpty(Stack **stack){
if(stack == NULL)
return 1;
else
return 0;
}

void push(Stack **stack,Matrix matrix){
//printf("Insert:%c %d %d\n",name,row,col);
Stack * new_stack = (Stack*) malloc(sizeof(Stack));
if(new_stack!=NULL){
new_stack->matrix = matrix;
new_stack->downPtr = (*stack);
(*stack) = new_stack;
}
}

// Check if stack is empty before pop function
Matrix pop(Stack **stack){
Stack *top = *stack;
Matrix matrix = top->matrix;
*stack = (*stack)-> downPtr;
free(top);
return matrix;
};

// Show the stack
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);
//printf("num:%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;
}

// Show all matrices
/*
for(int i=0;i<num;i++){
printf("%c %d %d\n",matrix[i].name,matrix[i].row,matrix[i].col);
}
*/

char command[10000]={0};
while(scanf("%s",command)!=EOF){
int ans=0;
int flag=1;
//stack of matrix
Stack* stack = NULL;

int len = strlen(command);
for(int i=0;i<len;i++){
if(command[i]=='(')
continue;
else if(command[i]==')'){
// Pop 2 matrices and calculate
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 the result on top of stack
push(&stack,m1);
}else{
// Find Matrix
int j=0;
for(j=0;j<num;j++)
if(command[i]==matrix[j].name)
break;
// Push Matrix on the top of stack
push(&stack,matrix[j]);
}
//show(&stack);
}
if(flag)
printf("%d\n",ans);
else
printf("error\n");

// Reset
memset(command,0,sizeof(command)/sizeof(char));
}

return 0;
}

評論




本站使用 Volantis 作為主題