Uva442 matrix chain multiplication (matrix chain multiplication)

Source: Internet
Author: User
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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.