矩阵链乘(UVA原题的链接单击这里哦???)
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 <bits/stdc++.h>
using namespace std;
class Matrix
{
public:
int a,b;//需设置成public,否则后面入栈操作时,给成员变量赋值无法改值
Matrix(int a=0, int b=0):a(a),b(b) {}
//↑↑这种情况需要有默认值
};
Matrix 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(), ans = 0;
bool ERROR = false;
for (int i = 0; i < len; ++i) {
if (isalpha(expr[i])) {s.push(m[expr[i]-'A']);}
else if (expr[i] == ')') { //如果从前往后扫描表达式时发现),则弹出两个Matrix判断并计算
Matrix temp2 = s.top(); s.pop();//注意temp2和temp1的出场顺序,因为是出栈,细心
Matrix temp1 = s.top(); s.pop();
if (temp1.b != temp2.a) {
ERROR = true;
break;
}
ans += temp1.a * temp1.b * temp2.b;
s.push(Matrix(temp1.a, temp2.b));
}
}
if(ERROR) cout << "error" << endl;
else cout << ans << endl;
}
return 0;
}