杭电 Problem-1082

Matrix Chain Multiplication

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)

Problem Description

Matrix multiplication problem is a typical example of dynamical programming.

Suppose you have to evaluate an expression like A B C D E ABCDE where A , B , C , D A,B,C,D and E 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 A be a 50 × 10 50\times10 matrix, B B a 10 × 20 10\times20 matrix and C C a 20 × 5 20\times5 matrix.
There are two different strategies to compute A B C ABC , namely ( A B ) C (AB)C and A ( B C ) A(BC) .
The first one takes 15000 15000 elementary multiplications, but the second one only 3500 3500 .

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

Input

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 ( 1 n 26 ) n(1\leqslant n\leqslant 26) , representing the number of matrices in the first part. The next n 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

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

Reference Code

#include<bits/stdc++.h>
using namespace std;
struct matrix{
    char name;
    int row,col;
}M[26],m1,m2;
int n,res;
bool flag;
string E;
stack <matrix> Q;
int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        cin>>M[i].name>>M[i].row>>M[i].col;
    while(cin>>E){
        if(E.size()==1){
            printf("0\n");
            continue;
        }
        res=0,flag=true;
        for(int i=0;i<E.size();i++){
            if(E[i]==')'){
                m1=Q.top(); Q.pop();
                m2=Q.top(); Q.pop();
                if(m1.row!=m2.col){
                    flag=false;
                    break;
                }
                res+=m2.row*m2.col*m1.col;
                m2.col=m1.col;
                Q.push(m2);
            }
            else if (E[i]!='('){
                for(int j=0;j<n;j++){
                    if(M[j].name==E[i]){
                        Q.push(M[j]);
                        break;
                    }
                }
            }
        }
        if(!flag) printf("error\n");
        else printf("%d\n",res);
    }
    return 0;
}

Tips

经典的数据结构题,用栈来进行括号匹配。
首先,通过观察可知,只需处理所有的右括号即可。所以,如果遇到的是矩阵,则将其压栈。如果遇到的是右括号,表示栈中至少存在两个等待相乘的矩阵。判断其是否可以相乘,如果不能,则直接break出去;否则将其需要的乘法次数加到res后继续向后匹配。如此匹配直到行末。

以下代码摘自刘汝佳《算法竞赛入门经典》第142页。其优于笔者代码的地方在于,它用矩阵名与字符A的ASCII码值之差作为name数组的下标,省去了查找的工作。

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

猜你喜欢

转载自blog.csdn.net/qq_43549984/article/details/86665336