#include <iostream>
#include <stdio.h>
#include <stack>
#define MAXN 36
#define MAXL 11000
char temp[MAXL];
struct Node
{
int a;
int b;//存储矩阵长和宽
}matrix[MAXN];//26个字母对应26个矩阵,个人喜欢36这个数字开成这样而已。。。
using namespace std;
stack <Node>s;//定义一个存储矩阵的栈
int main(void)
{
int T;//矩阵的数量
scanf("%d", &T);
while (T--)
{
char ch;
int temp_a, temp_b;
//getchar();
//scanf("%c %d %d", &ch, &temp_a, &temp_b);
cin >> ch >> temp_a >> temp_b;//不想用%c了太难用了!!!
matrix[ch - 'A'].a = temp_a;//因为字母有规律,因此我把它转化成数字来方便我把存储在一个结构数组中
matrix[ch - 'A'].b = temp_b;
}
while (scanf_s("%s", temp, MAXL) != EOF)
{
int sum = 0;
bool ok = true;//如果不能继续乘下去了
for (int i=0; temp[i]; i++)
if (temp[i] == ')')
{//遇到')'就弹出两个矩阵来相乘
Node x;
int x1 = s.top().a;
int x2 = s.top().b;
s.pop();
int y1 = s.top().a;
int y2 = s.top().b;
s.pop();
if ( x1 != y2)
{//矩阵的乘法是单向的!!!
ok = false;
break;
}
/*else if (x2 == y1)
{
sum += x1 * x2*y2;
x.a = x1;
x.b = y2;
s.push(x);
}*/
else if (x1 == y2)
{//AB和BA是不一样的,所以注意顺序!
sum += x1 * x2*y1;
x.a = y1;
x.b = x2;
s.push(x);//计算出来之后把计算出来的值压入栈中
}
}
else if (temp[i] >= 'A'&&temp[i] <= 'Z')
{//如果遇到字母就把这个字母对应的矩阵压入栈
s.push(matrix[temp[i] - 'A']);
}
if (ok)//如果能够正确的乘完,那就输出结果
printf("%d\n", sum);
else
printf("error\n");
}
return 0;
}
UVA - 442-Matrix Chain Multiplication
最新推荐文章于 2022-01-02 20:07:43 发布