题目:
给一个简单含矩阵和括号的表达式,判断这里面计算次数
思路:
用一个栈模拟一下就行,遇到右括号就一直出栈,直到遇见一个左括号。然后把中间计算得到的矩阵再次入栈。注意最后需要处理栈内剩余元素。
代码:
/*by kzl*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxx = 1e5+500;
const int INF = 0x3f3f3f3f;
typedef long long LL;
int n;
struct MY{
int x,y;
}node[maxx];
char c[2];
char s[maxx];
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%s",c);
int ch = c[0]-'A';
scanf("%d%d",&node[ch].x,&node[ch].y);
}
while(scanf("%s",s)!=EOF){
int len = strlen(s);
int j = 30;//30号元素之后记录新增节点
long long num = 0;
stack<int>sta;
bool flag = true;
int xx = 0,yy = 0;
for(int i=0;i<len;i++){
char ch = s[i];
if(!flag)break;
if(ch==')'){
while(!sta.empty()){
int tmp = sta.top();
sta.pop();
if(tmp==28){//28号元素记录(左括号
node[j].x = xx;node[j].y = yy;
sta.push(j++);
xx=0;yy=0;
break;
}
else {
if(xx==0&&yy==0){
xx = node[tmp].x;
yy = node[tmp].y;
}
else{
if(node[tmp].y!=xx){
flag = false;break;
}
num = num + node[tmp].x*xx*yy;
xx = node[tmp].x;
}
}
}
}
else if(ch=='('){
sta.push(28);
}
else {
sta.push(ch-'A');
}
}
if(!flag){
printf("error\n");
continue;
}
xx = 0,yy=0;
while(!sta.empty()){//注意栈里面最后剩余的元素也需要计算
int ch = sta.top();sta.pop();
if(xx==0&&yy==0)xx = node[ch].x,yy = node[ch].y;
else {
if(yy!=node[ch].x){
flag = false;
break;
}
num = num + xx*yy*node[ch].y;
yy = node[ch].y;
}
}
if(!flag)printf("error\n");
else printf("%lld\n",num);
}
return 0;
}