Matrix Chain Multiplication (UVa 442)

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 isarbitrary. However, the number of elementary multiplications needed
strongly depends on theevaluation 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 fora 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 ofmatrices in the first part. The
next n lines each contain one capital letter, specifying the name of thematrix, 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
本题比较基础,可以用一个栈来完成:遇到字母时入栈,遇到右括号时出栈计算,然后将结果入栈。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 1005
#define MAXN 2005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
typedef long long ll;
using namespace std;

struct st
{
    int a,b;
    st(int a=0,int b=0):a(a),b(b){}
};

stack<st>S;
int M[30],N[30];
int n;

int main()
{
    int i,j;
    char ch[3];
    char str[10010];
    scanf("%d",&n);
    for (i=0;i<n;i++)
    {
        scanf("%s",ch);
        scanf("%d%d",&M[ch[0]-'A'],&N[ch[0]-'A']);
    }
    while (~scanf("%s",str))
    {
        int len=strlen(str);
        bool No=false;
        int sum=0;
        for (i=0;i<len;i++)
        {
            if (isalpha(str[i]))
            {
                S.push(st(M[ str[i]-'A' ],N[ str[i]-'A' ]));
            }
            else if (str[i]==')')
            {
                st y=S.top();
                S.pop();
                st x=S.top();
                S.pop();
                if (x.b!=y.a)
                {
                    No=true;
                    break;
                }
                sum+=x.a*x.b*y.b;
                S.push(st(x.a,y.b));
            }
        }
        if (No)
            printf("error\n");
        else
            printf("%d\n",sum);
    }
    return 0;
}

时间: 2024-12-26 20:19:59

Matrix Chain Multiplication (UVa 442)的相关文章

例题6-3 Matrix Chain Multiplication ,Uva 442

这个题思路没有任何问题,但还是做了近三个小时,其中2个多小时调试 得到的经验有以下几点: 一定学会调试,掌握输出中间量的技巧,加强gdb调试的学习 有时候代码不对,得到的结果却是对的(之后总结以下常见错误) 能用结构体,就别用数组,容易出错(暂时还不知道为什么) 代码要规范,空格该有就要有 有些不规范表达式,不同编译器出现不同结果,注意应避免使用这类语句 像这道题主要坑在了第三点上,以后要注意避免 以下是AC代码 #include <cstdio> #include <stack>

UVa442 Matrix Chain Multiplication(矩阵链乘)

UVa442 Matrix Chain Multiplication(矩阵链乘) 题目链接:Uva442 题目描述:输入n个矩阵的维度和一个矩阵链乘的表达式,输出乘法的次数,如果乘法无法进行,则输出error. 题目分析: 栈对表达式求值有着特殊的作用,本题表达式简单,可以用一个栈来完成,遇到字母时入栈,遇到右括号时出栈并且计算,之后算出的结果入栈. <<<<<<<<<<<<<<<<<<<&l

ACM学习历程——UVA442 Matrix Chain Multiplication(栈)

Description Matrix Chain Multiplication  Matrix Chain Multiplication  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 perfo

Matrix Chain Multiplication (堆栈)

题目链接:https://vjudge.net/problem/UVA-442 题目大意:输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法的次数.如果乘法无法进行,输出error. 假定A是m*n的矩阵,B是n*p的矩阵,乘法次数为m*n*p.如果A的列数不等于B的行数,则乘法 无法进行. 例如A是50*10的,B是10*20的,C是20*5的,则(A(BC))的乘法次数为10*20*5(BC的乘法次数)+50*10*5((A(BC)的乘法次数)=3500 分析:本题的关键是解析表达式,本题的表

UVA - 442 Matrix Chain Multiplication(栈模拟水题+专治自闭)

题目: 给出一串表示矩阵相乘的字符串,问这字符串中的矩阵相乘中所有元素相乘的次数. 思路: 遍历字符串遇到字母将其表示的矩阵压入栈中,遇到‘)’就将栈中的两个矩阵弹出来,然后计算这两个矩阵的元素相乘的次数,累加就可以了. PS:注意弹出的矩阵表示的先后顺序. 代码: #include <bits/stdc++.h> #define inf 0x3f3f3f3f #define MAX 1000000000 #define mod 1000000007 #define FRE() freopen

UVa 442 Matrix Chain Multiplication(栈的应用)

题目链接: https://cn.vjudge.net/problem/UVA-442 1 /* 2 问题 3 输入有括号表示优先级的矩阵链乘式子,计算该式进行的乘法次数之和 4 5 解题思路 6 栈的应用,直接忽视左括号,每次只计算栈顶的两个矩阵会更加方便. 7 */ 8 #include<cstdio> 9 #include<cstring> 10 #include<stack> 11 #include<cctype> 12 using namespac

UVa442 Matrix Chain Multiplication (栈)

链接:http://acm.hust.edu.cn/vjudge/problem/19085分析:用栈来实现一个简单的表达式求值.输入表达式保证合法,比如(A(BC))把BC看成一个整体D那么(A(BC))就是AD,所以这些表达式都是在不断重复嵌套相同的结构A*B.遍历表达式,遇到字母则将对应矩阵压入栈中,遇到右括号则将栈顶两个矩阵弹出,判断是否能进行乘法,如果能则累加乘法次数,再将相乘后的矩阵压栈,如果不能则将error置为true,退出循环. 1 #include <iostream> 2

紫书例题6-3 (UVa 442)

题目地址:https://vjudge.net/problem/UVA-442 题目大意:汗颜,其实我是直接看紫书的中文题意的,大意就是计算两个矩阵乘法次数,设计线性代数知识,可自己百度矩阵乘法. 思路:栈+模拟,左括号开始入栈,右括号开始计算栈顶两个矩阵的乘法次数然后再将新矩阵的n,m入栈即可. AC代码: #include <iostream> #include <string> #include <stack> #include <cstring> u

UVA 442 二十 Matrix Chain Multiplication

Matrix Chain Multiplication Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu Submit Status Practice UVA 442 Appoint description:  System Crawler  (2015-08-25) Description Suppose you have to evaluate an expression like A*B*C*D*E