//4_4_2: Matrix Chain Multiplication 给出矩阵求计算次数 POJ2246 ZOJ1094
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
int x;
int y;
}matrix[26];
int main()
{
int i,n,x,y,ans,top = 0,flag;
char c,str[100];
node stack[50];
cin >> n;
for(i = 0;i < n;i ++)
{
cin >> c >> x >> y;
matrix[(int)(c - 'A')].x = x;
matrix[(int)(c - 'A')].y = y;
}
scanf("%c",&c);
while(cin.getline(str,100))
{
i = 0;
ans = 0;
flag = 0;
if(str[i] != '(')
{
printf("0\n");
continue;
}
while(str[i])
{
if(str[i] == '(')
i++;
else if(str[i] == ')')
{
if(stack[top - 1].y != stack[top].x)
{
flag = 1;
break;
}
else
{
ans += stack[top - 1].x * stack[top - 1].y * stack[top].y;
stack[top - 1].y = stack[top].y;
top --;
i ++;
}
}
else
{
top ++;
stack[top].x = matrix[(int)(str[i] - 'A')].x;
stack[top].y = matrix[(int)(str[i] - 'A')].y;
i++;
}
}
if(flag == 1)
printf("error\n");
else
printf("%d\n",ans);
}
return 0;
}
/*测试结果:通过POJ2246 ZOJ1094检测
9
A 50 10
B 10 20
C 20 5
D 30 35
E 35 15
F 15 5
G 5 10
H 10 20
I 20 25
A
0
B
0
C
0
(AA)
error
(AB)
10000
(AC)
error
(A(BC))
3500
((AB)C)
15000
(((((DE)F)G)H)I)
40500
(D(E(F(G(HI)))))
47500
((D(EF))((GH)I))
15125
请按任意键继续. . .
*/
POJ2246 ZOJ1094 Matrix Chain Multiplication
最新推荐文章于 2021-02-17 13:26:15 发布