Let's talk about:
In fact, this question is the most classic use of the stack data structure, that is, the evaluation of expressions. The difference is that the number of operations required for this operation is a matrix. During the entire parsing expression process, there are only three types of characters, one is '(', the other is ')', and the other is the number of operations. First, when you encounter '(', the stack pointer automatically adds one and sets the number of rows and columns of the element at the top of the stack to-1, so that it will not be confused with the normal number of operations. If you encounter an operation number, you must first determine whether the current top element of the stack is an operation number (of course, pay attention to the special case where the stack is empty ). If yes, the new calculation quantity and the stack top calculation quantity are directly calculated. Otherwise, the new calculation quantity is imported into the stack. The last case is ')'. At this time, the top of the stack must be the number of operations, and the next element at the top of the stack must be '(' so you only need to move the top element down one bit. Note that two consecutive operation numbers (at most two or three) may appear at the top of two stacks, because in this case, we also need to perform operations on these two elements. Repeat the above steps to complete the entire problem!
Source code:
# Include <stdio. h> # define maxn 26 + 5 typedef struct {int X; int y;} matrix; int main () {int N, I, P, wrong, ans; char C; matrix stack [maxn], current, data [maxn]; // freopen ("data", "r", stdin); scanf ("% d \ n ", & N); for (I = 0; I <n; I ++) scanf ("% C % d \ n", & C, & Data [I]. x, & Data [I]. y); While (1) {P = wrong = ans = 0; while (C = getchar ())! = '\ N') {If (C =' (') {stack [p]. X = stack [p]. y =-1; // The number of filling failures. Move the stack pointer up to P ++;} else if (C = ') {p --; stack P-1 X = stack [p]. x; // The top element of the stack moves down a stack [P-1]. y = stack [p]. y; If (P-2> = 0 & stack [P-2]. x! =-1) {// if the top of the stack has two consecutive operation numbers P --; If (stack [P-1]. y! = Stack [p]. x) Wrong = 1; ans + = stack P-1]. x * stack [P-1]. y * stack [p]. y; stack [P-1]. y = stack [p]. Y ;}} else {If (P = 0 | stack [P-1]. X =-1) {stack [p]. X = data [C-'a']. x; stack [p]. y = data [C-'a']. y; P ++;} else {If (stack P-1]. y! = Data [C-'a']. x) Wrong = 1; ans + = stack P-1]. x * stack [P-1]. y * Data [C-'a']. y; stack [P-1]. y = data [C-'a']. Y ;}}if (wrong) // wrong is 1, which indicates that printf ("error \ n") does not comply with the matrix algorithm during the operation "); else printf ("% d \ n", ANS); If (C = getchar () = EOF) break; else ungetc (C, stdin );} return 0 ;}
Matrix chain multiplication (stack expression evaluation)