简单题, 计算矩阵链乘需要的数乘次数
这类题最近做了几道, 都是采用遇到左括号忽略, 遇到右括号出栈, 其他字符压栈的操作
大概是表达式题的通用算法了把
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <list>
#include <cassert>
#include <iomanip>
using namespace std;
const int MAXN = 100000;
const int BASE = 100000000;
typedef long long LL;
/*
uva 442
*/
struct matrix{
int row,col;
matrix(){ }
matrix(int _row, int _col){
row = _row;
col = _col;
}
} ;
map<char,matrix> M;
stack<matrix> S;
matrix Pop(){
matrix res = S.top();
S.pop();
return res;
}
int main(){
// freopen("input2.txt","r",stdin);
int N;
char ch, str[MAXN];
matrix m;
cin >> N;
for(int i=0; i<N; i++){
cin >> ch >> m.row >> m.col;
M[ch] = m;
}
while( scanf("%s",str)!=EOF ){
int len = strlen(str), sum = 0;
bool isError = false;
for(int i=0; i<len; i++){
if( isalpha(str[i]) ){
S.push(M[str[i]]);
}
if( str[i]==')' ){
matrix m2 = Pop();
matrix m1 = Pop();
if( m1.col!=m2.row ){
isError = true;
break;
}
S.push(matrix(m1.row,m2.col));
sum += m1.row*m1.col*m2.col;
}
}
if( !isError ){
cout << sum << endl;
}else{
cout << "error" << endl;
}
}
return 0;
}