Uva-442-matrix chain Multiplication

Source: Internet
Author: User

<Span style = "font-size: 18px;"> ideas: </span>

The key to this question is the parsing expression. The expression in this question is relatively simple and can be completed using a stack --->

When a letter is encountered, it is written into the stack; when there is a right brace, It is computed out of the stack, and then the new matrix is clicked into the stack!

In this case, if the number of columns of A is not equal to the number of rows of B, multiplication cannot be performed !!! Note!

The Code is as follows:

# Include <cstdio> # include <cstring> # include <iostream> # include <stack> # include <string> using namespace STD; struct Ma {int H, L; // horizontal and column! MA (int l = 0, int h = 0): L (L), H (h) {}} M [26]; int main () {int N; cin> N; For (INT I = 0; I <n; I ++) {string name; CIN> name; cin> M [name [0]-'a']. h> M [name [0]-'a']. l;} string SEN; while (CIN> Sen) {stack <Ma> q; int flag = 0, Len = Sen. length (); bool error = false; int ans = 0; For (INT I = 0; I <Len; I ++) {If (isalpha (Sen [I]) // if it is a letter, go to the stack! Q. push (M [Sen [I]-'a']); else if (Sen [I] = ') {Ma m2 = Q. top (); // The first to last! Q. Pop (); MA M1 = Q. Top (); // The second to the last! Q. Pop (); If (m1.h! = M2.l) // if the length of the last 1st columns is not equal to the length of the last 1st columns, exit! {// That is, the horizontal length of! = Column Length of B! Error = true; flag = 1; break;} ans + = m1.h * m1.l * m2.h; q. push (MA (m1.h, m2.l); // Add the new vertex to the stack!} If (FLAG) break; // There is no need to perform cyclic operations!} 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.