题意:给定A-Z若干的矩阵,以及一些表达式,根据表达式求出所有矩阵相乘的次数,若中间出现不符合要求的情况,则输出“error”
解法:用栈进行模拟,代码写的奇丑无比。
#include<stdio.h>
#include<string.h>
#include<stack>
#define MAXN 100000
using namespace std;
struct node
{
int x,y;
}p[300];
char s[MAXN],ch;
int main()
{
int n,i,j,k,sum;
bool error;
scanf("%d",&n);
getchar();
for(i=0; i<n; i++) //读入n个矩阵,并按照顺序存储
{
scanf("%c",&ch);
scanf("%d %d",&p[ch-'A'].x,&p[ch-'A'].y);
getchar();
}
while(gets(s)!=NULL)
{
n=26;
sum=0;
error=false;
stack<int>sta;
for(i=0; i<strlen(s); i++)
{
if(s[i]=='(') sta.push(-1); //当读入一个“(”时,将-1入栈,表示一个边界
else if(s[i]==')') //读入一个“)”时,则把栈中的元素进行出栈操作
{
int t1=sta.top(); sta.pop();
if(t1==-1) continue;
int t2=sta.top(); sta.pop();
p[n]=p[t1];
while(t2!=-1)
{
if(p[t2].y==p[n].x)
{
sum+=p[t2].x*p[t2].y*p[n].y;
p[n].x=p[t2].x;
}
else
{
error=1;
break;
}
t2=sta.top(); sta.pop();
}
if(error) break;
sta.push(n++);
}
else sta.push(s[i]-'A');
}
if(!sta.empty())
{
int t1=sta.top(); sta.pop();
int x=p[t1].x,y=p[t1].y;
while(!sta.empty())
{
t1=sta.top(); sta.pop();
if(p[t1].y==x)
{
sum+=p[t1].x*x*y;
x=p[t1].x;
}
else
{
error=1;
break;
}
}
}
if(error) printf("error\n");
else printf("%d\n",sum);
}
return 0;
}