您的位置:首页 > 大数据 > 人工智能

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

2013-08-02 16:27 525 查看


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 (

), 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: