这道题比较简单,考察栈在表达式求值中的应用,看了书上代码之后才发现我考虑复杂了。。。其实题目中括号中只有个两个矩阵,我以为会有多个矩阵,所以将"("(用(0,0)代替)也压入了堆栈,用来判断什么时候停止合并。那样的话就特别特别简单了。。。
输入数据少打了个回车找了半天bug。。。
复杂版:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 5;
typedef pair<int,int> P;
int main(){
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
int n,a,b;
char c,s[maxn];
scanf("%d\n",&n);
P d[26];
while(n--){
scanf("%c %d %d\n",&c,&a,&b);
d[c-'A'] = P(a,b);
}
while(fgets(s,maxn,stdin)){
stack<P>sta;
int len = strlen(s) - 1,mark = 1,r = 0,c = 0,num = 0;
for(int i = 0;i < len && mark;i++){
if(s[i] == '(') sta.push(P(0,0));
else if(s[i] == ')'){
int ok = 1;
while(ok && sta.size() > 2){
P b = sta.top();sta.pop();
P a = sta.top();sta.pop();
if(a.second != b.first){ mark = 0; break; }
r = a.first,c = b.second;
num += r*a.second*c;
if(!sta.top().first){ sta.pop(); ok = 0; }
sta.push(P(r,c));
}
}
else sta.push(d[s[i]-'A']);
}
if(!mark) puts("error");
else printf("%d\n",num);
}
return 0;
}
简单版:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 5;
typedef pair<int,int> P;
int main(){
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
int n,a,b;
char c,s[maxn];
scanf("%d\n",&n);
P d[26];
while(n--){
scanf("%c %d %d\n",&c,&a,&b);
d[c-'A'] = P(a,b);
}
while(fgets(s,maxn,stdin)){
stack<P>sta;
int len = strlen(s) - 1,mark = 1,r = 0,c = 0,num = 0;
for(int i = 0;i < len && mark;i++){
if(s[i] == ')'){
P b = sta.top();sta.pop();
P a = sta.top();sta.pop();
if(a.second != b.first){ mark = 0; break; }
r = a.first,c = b.second;
num += r*a.second*c;
sta.push(P(r,c));
}
else if(s[i] != '(') sta.push(d[s[i]-'A']);
}
if(!mark) puts("error");
else printf("%d\n",num);
}
return 0;
}