题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=383
题目大意:矩阵链乘,学过线性代数应该都知道。
分析:利用栈,每次遇到字母就加入到栈中,每次遇到)就把栈顶开始的两个元素拿出来计算,然后再加入到栈中,因为输入的括号肯定是匹配的,所以根本就不用考虑(,遇到直接跳过就好了。
ac代码
#include<cstdio>
#include<stack>
#include<cstring>
using namespace std;
struct Matr
{
int a;
int b;
}matr[30];
int main()
{
int n;
scanf("%d", &n);
getchar();
for(int i = 1; i <= n; i++)
{
char c;
scanf("%c", &c);
int k = c - 'A';
scanf("%d %d", &matr[k].a, &matr[k].b);
getchar();
}
char str[100];
while(scanf("%s", str) != EOF)
{
stack<Matr> s;
int len = strlen(str);
int sum = 0;
int flag = 1;
for(int i = 0; i < len; i++)
{
if(str[i] >= 'A' && str[i] <= 'Z')s.push(matr[str[i] - 'A']);
else if(str[i] == ')')
{
Matr x, y, z;
y = s.top();
s.pop();
x = s.top();
s.pop();
//printf("%d %d %d %d\n", x.a, x.b, y.a, y.b);
if(x.b != y.a)
{
flag = 0;
break;
}
else
{
sum = sum + x.a * x.b * y.b;
z.a = x.a;
z.b = y.b;
s.push(z);
//printf("aaaaaaaaaaaaaa\n");
}
}
}
if(flag)printf("%d\n", sum);
else printf("error\n");
}
return 0;
}