题意
矩阵链乘
求乘法次数
思路
利用栈<结构体>
遇到字母入栈, 遇到 ‘)’ 出栈并计算, 结果再次入栈
AC代码
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
using namespace std;
struct matrix
{
int a, b;
}m[30], m1, m2, mm;
stack<matrix> stk;
int main()
{
int T;
char c;
string s;
scanf("%d",&T);
getchar();
while(T--){
scanf("%c ",&c);
//m[c-'A'].name = c;
scanf("%d %d",&m[c-'A'].a,&m[c-'A'].b);
getchar();
}
int re, len;
bool err;
while( cin >> s ){
re = 0;
len = s.length();
err = false;
for( int i = 0; i < len; i++ ){
if( isalpha(s[i]) )
stk.push( m[s[i]-'A'] );
else if( s[i] == ')' ){
m2 = stk.top();
stk.pop();
m1 = stk.top();
stk.pop();
if( m1.b != m2.a ){
//cout << "* " << m1.b << " " << m2.a <<endl;
err = true;
break;
}
re += m1.a * m1.b * m2.b;
mm.a = m1.a, mm.b = m2.b;
stk.push(mm);
}
}
if(err) cout << "error" << endl;
else cout << re << endl;
while(!stk.empty())
stk.pop();
}
return 0;
}