UVa 442/HDU 1082/ZOJ 1094 Matrix Chain Multiplication(模拟&栈)

442 - Matrix Chain Multiplication

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=103&page=show_problem&problem=383

http://acm.hdu.edu.cn/showproblem.php?pid=1082

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=94


Suppose you have to evaluate an expression like A*B*C*D*E where A,B,C,D and E are matrices. Since matrix multiplication is associative, the order in which multiplications are performed is arbitrary. However, the number of elementary multiplications needed strongly depends on the evaluation order you choose.

For example, let A be a 50*10 matrix, B a 10*20 matrix and C a 20*5 matrix. There are two different strategies to compute A*B*C, namely (A*B)*C and A*(B*C).

The first one takes 15000 elementary multiplications, but the second one only 3500.

Your job is to write a program that determines the number of elementary multiplications needed for a given evaluation strategy.

Input Specification

Input consists of two parts: a list of matrices and a list of expressions.

The first line of the input file contains one integer n ( tex2html_wrap_inline28 ), representing the number of matrices in the first part. The next n lines each contain one capital letter, specifying the name of the matrix, and two integers, specifying the number of rows and columns of the matrix.

The second part of the input file strictly adheres to the following syntax (given in EBNF):

SecondPart = Line { Line } <EOF>
Line       = Expression <CR>
Expression = Matrix | "(" Expression Expression ")"
Matrix     = "A" | "B" | "C" | ... | "X" | "Y" | "Z"

Output Specification

For each expression found in the second part of the input file, print one line containing the word "error" if evaluation of the expression leads to an error due to non-matching matrices. Otherwise print one line containing the number of elementary multiplications needed to evaluate the expression in the way specified by the parentheses.

Sample Input

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
B
C
(AA)
(AB)
(AC)
(A(BC))
((AB)C)
(((((DE)F)G)H)I)
(D(E(F(G(HI)))))
((D(EF))((GH)I))

Sample Output

0
0
0
error
10000
error
3500
15000
40500
47500
15125

思路:

1. 注意题目要求的是 " the number of elementary multiplications",即做乘法的次数。

在矩阵乘法AB=C中(前提:A的列数=B的行数),C中每个元素需要做(A的列数)次乘法,而C中有(A的行数)*(B的列数)个元素,

所以每次做了(A的行数)*(A的列数)*(B的列数)次乘法。

2. 这题如果有看过编译器原理的话更好——在看懂扩展巴科斯-瑙尔范式(EBNF)的同时得知我们需要用栈来实现:

用一个栈s1操作括号,另一个栈s2操作矩阵。同时,用s1来操纵s2(技巧:插入一个标记元素'#')。


PS:也可以用递归做。


完整代码:

/*UVaOJ: 0.018s*/
/*HDU: 0ms,244KB*/
/*ZOJ: 0ms,184KB*/

#include <cstdio>
#include <stack>
using namespace std;

struct node
{
	int m, n;
} matrix[200];

char s[1000];

int main()
{
	int n, i, sum;
	char ch;
	bool b;
	scanf("%d", &n);
	while (n--)
	{
		getchar();//开头那个不用记
		scanf("%ch", &ch);
		scanf("%d%d", &matrix[ch].m, &matrix[ch].n);
	}
	node temp, temp2;
	while (~scanf("%s", s))//读一整行,包括'\0'
	{
		sum = 0;
		b = true;
		stack<char> s1;//存括号
		stack<node> s2;//存矩阵
		for (i = 0; s[i] != '\0'; i++)
		{
			if (s[i] == '(')
				s1.push(s[i]);
			else if (s[i] == ')')
                //注意:遇到右括号时相邻左边肯定有一个矩阵
			{
				s1.pop();//'#'出栈
				s1.pop();//'('出栈
				while (!s1.empty() && s1.top() != '(')
                                     //s1.top() != '('判断左边的左边是否有一个矩阵
				{
					temp = s2.top();
					s2.pop();
					temp2 = s2.top();
					if (temp2.n != temp.m)
					{
						b = false;
						break;
					}
					sum += temp2.m * temp2.n * temp.n;
					temp2.n = temp.n;
					s2.pop();
					s2.push(temp2);
					s1.pop();//'#'出栈
				}
				s1.push('#');
			}
			else
			{
				if (!s1.empty() && s1.top() != '(')
                                //s1.top() != '('判断左边的左边是否有一个矩阵
				{
					temp = s2.top();
					if (temp.n != matrix[s[i]].m)
					{
						b = false;
						break;
					}
					sum += temp.m * temp.n * matrix[s[i]].n;
					//新矩阵:行数=左边矩阵行数,列数=右边矩阵的列数
					temp.n = matrix[s[i]].n;
					s2.pop();
					s2.push(temp);
				}
				else
				{
					s2.push(matrix[s[i]]);
					s1.push('#');
				}
			}
		}
		if (b)
			printf("%d\n", sum);
		else
			printf("error\n");
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值