Matrix Chain multiplication (expression evaluation stack operation)

Source: Internet
Author: User

title Link: Chain Multiplication

Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 1382 Accepted Submission (s): 905

Problem Descriptionmatrix multiplication problem is a typical example of dynamical programming.

Suppose you has to evaluate a expression like a*b*c*d*e where a,b,c,d and E is matrices. Since matrix multiplication is associative, the order of which multiplications is performed. However, the number of elementary multiplications needed strongly depends on the evaluation order you choose.
For example, let A is a 50*10 matrix, B a 10*20 matrix and C a 20*5 matrix.
There is different strategies to compute a*b*c, namely (A*B) *c and a A * (B*C).
The first one takes 15000 elementary multiplications, but the second one is only 3500.

Your job is to write a program This determines the number of elementary multiplications needed for a given evaluation stra Tegy.

Inputinput consists of parts:a list of matrices and a list of expressions.
The first line of the input file contains one integer n (1 <= n <=), representing the number of matrices in the F Irst part. The next n lines each contain one capital letter, specifying the name of the matrix, and the integers, specifying the numb Er of rows and columns of the matrix.
The second part of the input file strictly adheres to the following syntax (given in EBNF):

Secondpart = line {line} <EOF>
line = Expression <CR>
Expression = Matrix | "(" Expression expression ")"
Matrix = "A" | "B" | "C" | ... | "X" | "Y" | Z

Outputfor each expression found in the second part of the input file, print one line containing the word "error" if Evalua tion of the expression leads to a error due to non-matching matrices. Otherwise print one line containing the number of elementary multiplications needed to evaluate the expression in the specified by the parentheses.

Sample input9a 10B 20C 5D 35E 15F 5G 5 10H (AA) (AB) (AC) (A (BC)) ((AB) C) ((((F) (D) H) (b) (F (G (HI))))) ((D (EF)) ((GH) I))

Sample output000error10000error350015000405004750015125

Sourceuniversity of ULM Local Contest 1996 Test Instructions: Here is a description of the structural function of the structure of the body weight of the more magical writing; see Rujia great God's code problem: A water problem, pay attention to the question of expression evaluation should immediately think of the stack to implement their own AC code
1#include <cstdio>2#include <cstring>3#include <string>4#include <algorithm>5#include <map>6#include <iostream>7 using namespacestd;8 #defineN 309 #defineM 50000Ten structmnode{ One     intm; A     intN; - }mm[n]; - Mnode stk[m]; the  - intMain () - { -     intT; +      while(~SCANF ("%d",&t)) -     { +map<Char,int>MP; A          for(inti =0; I < T; i++) at         { -             Charch; -             intm, N; - GetChar (); -scanf"%c%d%d",&ch,&m,&n); -MP[CH] =i; inMM[I].M =m; -MM[I].N =N; to         } +         Charml[ +]; -          while(~SCANF ("%s", ml)) the         { *         inttop =0; $         intAns =0;Panax Notoginseng         BOOLFlag =1; -          for(inti =0; I < strlen (ml); i++) the         { +             if(ml[i]<='Z'&&ml[i]>='A'){ A Mnode TM; theTM.M =mm[mp[ml[i]]].m; +TM.N =MM[MP[ML[I]]].N; -stk[top++] =TM; $             } $             Else if(ml[i]==')'){ - Mnode tm1,tm2,tm3; -TM2 = stk[--top]; theTM1 = stk[--top]; -                 if(TM1.N!=TM2.M) {Puts ("Error"); Flag =0; Break; }WuyiTM3.M =tm1.m; theTM3.N =TM2.N; -ans+=tm1.m*tm1.n*TM2.N; Wustk[top++] =TM3; -             } About         } $         if(flag) printf ("%d\n", ans); -         } -     } -     return 0; A}

Rujia the code of the great God, notice how the constructor is written, indicating that if no parameters are automatically default two parameter values are 0

1#include <cstdio>2#include <stack>3#include <iostream>4#include <string>5 using namespacestd;6 structmatrix{7     intA, B;8Matrix (intA =0,intb =0): A (a), B (b) {}9}m[ -];TenStack<matrix>s; One  A intMain () - { -     intN; theCin>>N; -      for(inti =0; I < n; i++){ -         stringname; -Cin>>name; +         intK = name[0]-'A'; -Cin>>m[k].a>>m[k].b; +     } A     stringexpr; at      while(cin>>expr) { -         intLen =expr.length (); -         BOOLError =false; -         intAns =0; -          for(inti =0; i < Len; i++){ -             if(Isalpha (Expr[i])) S.push (m[expr[i]-'A']); in             Else if(expr[i]==')'){ -Matrix m2 (); S.pop (); toMatrix M1 (); S.pop (); +                 if(m1.b!=m2.a) {error =true; Break;} -Ans + = m1.a*m1.b*m2.b; the S.push (Matrix (m1.a,m2.b)); *             } $         }Panax Notoginseng         if(Error) printf ("error\n");Elseprintf"%d\n", ans); -     } the     return 0; +}

Matrix Chain multiplication (expression evaluation stack operation)

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: 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.