Matrix Chain Multiplication, UVa442

Matrix Chain Multiplication

Suppose you have to evaluate an expression like A*B*C*D*E where A,B,C,D and E are matrices. Since matrix multiplication is associative, the order in which multiplications are performed is arbitrary. However, the number of elementary multiplications needed strongly depends on the evaluation order you choose.

For example, let A be a 50*10 matrix, B a 10*20 matrix and C a 20*5 matrix. There are two different strategies to compute A*B*C, namely (A*B)*C and A*(B*C).

The first one takes 15000 elementary multiplications, but the second one only 3500.

Your job is to write a program that determines the number of elementary multiplications needed for a given evaluation strategy.

Input Specification

Input consists of two parts: a list of matrices and a list of expressions.

The first line of the input file contains one integer n ( tex2html_wrap_inline28 ), representing the number of matrices in the first part. The next n lines each contain one capital letter, specifying the name of the matrix, and two integers, specifying the number 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"

Output Specification

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

Sample Input

9
A 50 10
B 10 20
C 20 5
D 30 35
E 35 15
F 15 5
G 5 10
H 10 20
I 20 25
A
B
C
(AA)
(AB)
(AC)
(A(BC))
((AB)C)
(((((DE)F)G)H)I)
(D(E(F(G(HI)))))
((D(EF))((GH)I))

Sample Output

0
0
0
error
10000
error
3500
15000
40500
47500
15125

代碼:

#include <string>
#include <cstdio>
#include <stack>
#include <cstring>
#include <iostream>
using namespace std;

//1.定義一個結構體,存儲矩陣行列數
//2.題目中說每個大寫字符代表一個矩陣,並且n小於等於26,所以結構體數組大小定義爲26就好
struct Matrix{
    int a;
    int b;
}m[26];

int main(int argc, const char * argv[]) {
   
    int n;        //n個矩陣
    scanf("%d", &n);
    getchar();
    char c; int a, b;
    for (int i = 0; i < n; i++) { //由於輸入數據包含字符和數字,所以需要使用getchar()讀取回車
        scanf("%c %d %d", &c, &a, &b);
        getchar();
        m[c - 'A'].a = a;
        m[c - 'A'].b = b;
    }
    string s;
    while (cin >> s) {
        if (s.length() == 1) { //單個矩陣均輸出0
            printf("0\n");
            continue;
        }
        int sum = 0;           //存儲結果
        int ok = 1;            //標記,如果結果爲error則把OK賦值0,否則爲1
        struct Matrix x, y, z;
        stack<Matrix> Stack;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == '(') {
                continue;
            }
            if (s[i] == ')') {
                
                x = Stack.top();
                Stack.pop();   //獲取到棧頂元素(棧頂矩陣)立即把棧頂元素排除棧外,不然無法獲取第二個矩陣,
                
                y = Stack.top(); //在此之前一定要把原來棧頂的矩陣排除棧頂,否則兩次獲取的矩陣是同一個矩陣
                Stack.pop();
                
                //這一步不能省掉,要把兩個矩陣形成的新矩陣壓入到棧中
                z.a = y.a;
                z.b = x.b;
                Stack.push(z);
                
                //如果第一個矩陣的列號不等於第二個矩陣的行號,那麼這兩個矩陣無法進行矩陣積運算,把ok標記爲0
                if (x.a != y.b) {
                    ok = 0;
                    break;
                } else {      //兩個矩陣能夠進行矩陣積運算
                    sum = sum + x.a * x.b * y.a;
                    continue;
                }
            }
            //前面兩個if語句如果都不滿足,說明該s[i]爲大寫字符
            Stack.push(m[s[i] - 'A']);
        }
        if (ok) {
            printf("%d\n", sum);
        } else {
            printf("error\n");
        }
    }
    return 0;
}

另附上大神劉汝佳的代碼:

#include<cstdio>
#include<stack>
#include<iostream>
#include<string>
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) printf("error\n"); else printf("%d\n", ans);
  }

  return 0;
}




發佈了78 篇原創文章 · 獲贊 12 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章