Uva442 matrix chain multiplication (matrix chain multiplication)
Link: uva442
Description: Enter n matrix dimensions and a matrix chain multiplication expression. The number of multiplication times is output. If multiplication cannot be performed, an error is output.
Question Analysis:
Stack has a special role in expression evaluation. The expression in this question is simple and can be completed using a stack. When a letter is encountered, the stack is written into the stack, and when the right brace is encountered, the stack is output and calculated, then the calculated result is written into the stack.
<<
Reference code:
// Matrix chain multiplication. CPP # include <iostream> # include <string> # include <stack> using namespace STD; struct matrix {int A, B; matrix (int A = 0, int B = 0): A (a), B (B) {}} M [26]; stack <matrix> S; int main () {int N; CIN> N; for (INT I = 0; I <n; I ++) {string name; CIN> name; int K = Name [0]-'A '; cin> M [K]. a> M [K]. b;} string expr; while (CIN> expr) {int Len = expr. length (); bool error = false; int ans = 0; For (INT I = 0; I <Len; I ++) {If (isalpha (expr [I]) s. push (M [expr [I]-'a']); else if (expr [I] = ') {matrix m2 = S. top (); S. pop (); matrix M1 = S. top (); S. pop (); If (m1. B! = M2.a) {error = true; break;} ans + = m1.a * m1. B * m2. B; S. push (matrix (m1.a, m2. B) ;}} if (error) cout <"error" <Endl; else cout <ans <Endl;} return 0 ;}