题意:
矩阵相乘,看白书
要点:
用栈做,话说纯c真麻烦,要用c++中的STL,但strlen又要用c中的string.h。注意题目叙述,一个括号中最多只有两个矩阵相乘
代码如下:
#include<cstdio>
#include<string>
#include<stack>
#include<string.h> //为了用strlen
using namespace std;
typedef struct
{
int m;
int n;
}matrix;
stack<matrix> s;
int main()
{
int t,i;
matrix math[350];
while (~scanf("%d", &t))
{
char ch[50]; //防止\n的干扰,直接读入字符会读入\n
for (i = 0; i < t; i++)
{
scanf("%s", ch);
scanf("%d%d", &math[ch[0]].m, &math[ch[0]].n);
}
char ans[500];
while(~scanf("%s",ans))
{
bool error = false;
int num=0;
int len = strlen(ans);
for (i = 0; i < len; i++)
{
if (isalpha(ans[i])) //isalpha函数判断是否是英文字母,小写返回2,大写返回1,不是返回0
s.push(math[ans[i]]);
else if (ans[i] == ')')
{
matrix m1 = s.top(); s.pop();//题目上说最多两个矩阵连乘
matrix m2 = s.top(); s.pop();
if (m1.m != m2.n) {error = true; break;} //注意这里AB先出来的是B,所以谁的m和谁的n容易搞反
num += m2.m*m1.m*m1.n;
matrix m3 = { m2.m,m1.n };
s.push(m3); //一个括号算完后将一个新的矩阵压入栈
}
}
if (error)
printf("error\n");
else
printf("%d\n", num);
}
}
return 0;
}