442 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 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
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 (1 ≤ n ≤ 26), 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
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
Universidad de Valladolid OJ: 442 – Matrix Chain Multiplication 2/2
(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

栈模拟

我们先用一个结构体储存每个矩阵的长和宽。然后我们开始对读入的每一个字符串进行扫描,当我们遇到(的时候直接忽略,遇到)的时候讲栈顶的两个元素弹出进行计算,每次计算的时候我们需要判断这两个矩阵是否满足相乘的条件,矩阵相乘的条件为第一个矩阵的宽等于第二个矩阵的长,然后ans根据题目中要求的进行累加。当既不是(也不是)的时候我们将这个矩阵入栈。

#include<stack>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 30
using namespace std;
int read()
{
    ,f=; char ch=getchar();
    ;ch=getchar();}
    +ch-',ch=getchar();
    return x*f;
 }
bool flag;
char ch;
string ss;
struct Node
{
    int x,y;
    Node(,):x(x),y(y){}
}node[N];
stack<Node>s;
int main()
{
    int n=read(),a,ans;
    ;i<=n;i++)
    {
        scanf("%c",&ch);
        a=ch-;
        node[a].x=read(),node[a].y=read();
    }
    while(cin>>ss)
    {
        int l=ss.length();
        flag=;
        ;i<l;i++)
        {
            if(ss[i]==')')
            {
                Node m2=s.top(); s.pop();
                Node m1=s.top(); s.pop();
                if(m1.y!=m2.x) {flag=true;break;}
                else
                {
                    ans+=m1.x*m1.y*m2.y;
                    s.push(Node(m1.x,m2.y));
                }
            }
            else
            if(ss[i]!='(')
            {
                a=ss[i]-;
                s.push(Node(node[a].x,node[a].y));
            }
        }
        if(flag) printf("error\n");
        else printf("%d\n",ans);
    }
    ;
}

UVA——442 Matrix Chain Multiplication的更多相关文章

  1. UVa 442 Matrix Chain Multiplication(矩阵链,模拟栈)

    意甲冠军  由于矩阵乘法计算链表达的数量,需要的计算  后的电流等于行的矩阵的矩阵的列数  他们乘足够的人才  非法输出error 输入是严格合法的  即使仅仅有两个相乘也会用括号括起来  并且括号中 ...

  2. stack UVA 442 Matrix Chain Multiplication

    题目传送门 题意:给出每个矩阵的行列,计算矩阵的表达式,如果错误输出error,否则输出答案 分析:表达式求值,stack 容器的应用:矩阵的表达式求值A 矩阵是a * b,B 矩阵是b * c,则A ...

  3. UVa 442 Matrix Chain Multiplication(栈的应用)

    题目链接: https://cn.vjudge.net/problem/UVA-442 /* 问题 输入有括号表示优先级的矩阵链乘式子,计算该式进行的乘法次数之和 解题思路 栈的应用,直接忽视左括号, ...

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

    题目: 给出一串表示矩阵相乘的字符串,问这字符串中的矩阵相乘中所有元素相乘的次数. 思路: 遍历字符串遇到字母将其表示的矩阵压入栈中,遇到‘)’就将栈中的两个矩阵弹出来,然后计算这两个矩阵的元素相乘的 ...

  5. 例题6-3 Matrix Chain Multiplication ,Uva 442

    这个题思路没有任何问题,但还是做了近三个小时,其中2个多小时调试 得到的经验有以下几点: 一定学会调试,掌握输出中间量的技巧,加强gdb调试的学习 有时候代码不对,得到的结果却是对的(之后总结以下常见 ...

  6. UVA 442 二十 Matrix Chain Multiplication

    Matrix Chain Multiplication Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %l ...

  7. Matrix Chain Multiplication[HDU1082]

    Matrix Chain Multiplication Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (J ...

  8. UVa442 Matrix Chain Multiplication

    // UVa442 Matrix Chain Multiplication // 题意:输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法的次数.假定A和m*n的,B是n*p的,那么AB是m*p的,乘法 ...

  9. Matrix Chain Multiplication(表达式求值用栈操作)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1082 Matrix Chain Multiplication Time Limit: 2000/100 ...

随机推荐

  1. JAVA中的类

    节选自:http://www.cnblogs.com/dolphin0520/p/3811445.html 1. 成员内部类是依附外部类而存在的,也就是说,如果要创建成员内部类的对象,前提是必须存在一 ...

  2. json序列化datetime类型数据

    错误描述: import jsonimport datetime a = datetime.datetime.now()print(a) b = json.dumps(a)print(b) 如上代码, ...

  3. 数据库——pymysql模块的使用(13)

    1.基本用法——建立链接,获取游标,执行sql语句,关闭 建立远程链接账号和权限 mysql> grant all on *.* to '; Query OK, rows affected, w ...

  4. 3D U-Net卷积神经网络

    3D U-Net这篇论文的诞生主要是为了处理一些块状图(volumetric images),基本的原理跟U-Net其实并无大差,因为3D U-Net就是用3D卷积操作替换了2D的,不过在这篇博文中我 ...

  5. CPU指令集不同导致的core分析

    最近程序需要支持CGSL系统运行,测试中发现相同操作系统的两台机器,编译机运行正常,测试机coredump.core信息汇总如下,可以看出是由于测试机不支持编译后的指令导致的问题: Program t ...

  6. React01

    目录 React-day01 入门知识 React介绍 官网 React开发环境初始化 SPA 脚手架初始化项目(方便,稳定)* 通过webpack进行初始化 配置镜像地址 开发工具配置 元素渲染 组 ...

  7. golang中从一个日期开始往后增加一段时间

    废话少说上code, 这个是从当前日期开始,往后增加一个月时间 package main import ( "fmt" "time" ) func main() ...

  8. favicon.ico generator

    favicon.ico generator https://www.favicon-generator.org/ https://www.favicon.cc/ https://www.favicon ...

  9. Oracle在登陆时被告知用户被锁,如何解决?

    在登陆时被告知test用户被锁 1.用dba角色的用户登陆,进行解锁,先设置具体时间格式,以便查看具体时间 SQL> alter session set nls_date_format=’yyy ...

  10. Android程序猿必须警示的13个坑

        Android开发中,犯错是难免的,不犯错是不正常的,但是犯了错以后,我们必须时刻谨记这些坑,避免再次被坑,下面小编整理了13个,日常工作中,比较常见且易犯的错误,分享给大家.    1.类的 ...