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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值