简单题,利用栈来进行操作。读取指令,如果读取到的指令仅仅由一个字母组成,那么就查找我们是否已经保存了该矩阵的信息,如果保存了,那么不需要做任何的乘法操作,直接输出0,如果没有保存,那么就直接输出"error"。对于长度不为1的指令,依次读取相应的信息,如果是左括号,那么就往栈1中存入一个行列均为-1的矩阵,如果是其他的非右括号的符号,那么就存入相应的矩阵,如果读入的是右括号,那么就从栈中依次弹出矩阵到栈2,直到遇到左括号所对应的矩阵。然后对栈2中的矩阵进行处理,依次出栈2,判断是否能够进行乘法操作,如果不能进行,则输出"error",结束当前的处理,如果可以,就一直处理,同时更新总的乘法数,对于当前产生的最终结果要存入栈1,以便进行后续的计算使用。
源代码如下:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<iomanip>
using namespace std;
int n;
typedef struct matrix{
int row, col;
bool operator!=(matrix a){
if (row != a.row || col != a.col) return true;
return false;
}
}matrix;
int main(){
int n;
while (cin >> n){
vector<matrix> data;
map<char, int> ch2ind;
for (int i = 0; i < n; i++){
matrix temp;
char name;
cin >> name >> temp.row >> temp.col;
data.push_back(temp);
ch2ind[name] = i;
}
string instruct;
while (cin >> instruct){
int amount = 0;
bool flag_e = false;
if (instruct.size() == 1){
char aim = instruct[0];
if (ch2ind.find(aim) != ch2ind.end()) cout << "0" << endl;
else cout << "error" << endl;
continue;
}
else{
stack<matrix> st;
stack<matrix> st_a;
matrix left_k;
left_k.row = -1;
left_k.col = -1;
for (int i = 0; i < instruct.size(); i++){
if (instruct[i] == '('){
st.push(left_k);
}
else if (instruct[i]!=')'){
st.push(data[ch2ind[instruct[i]]]);
}
else{//')'
while (!st.empty()&&st.top() != left_k){
st_a.push(st.top());
st.pop();
}
st.pop();
matrix temp1 = st_a.top();
st_a.pop();
while (!st_a.empty()){
matrix temp2 = st_a.top();
st_a.pop();
if (temp1.col != temp2.row){
flag_e = true;
cout << "error" << endl;
break;
}
else{
amount += temp1.row*temp1.col*temp2.col;
temp1.col = temp2.col;
}
}
if (flag_e) break;
st.push(temp1);
}
}
if (!flag_e) cout << amount << endl;
}
}
}
//system("pause");
return 0;
}