C - Matrix Chain Multiplication

Crawling in process... Crawling failed Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu

Description

 

 

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 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
题目大意:给你若干个矩阵(x*y),然后给你若干种计算公式,问你在该种计算公式情况下能否进行矩阵乘法运算,
若能进行,输出需进行乘法的次数。
思路分析:首先要对矩阵的乘法运算有一定了解,首先,A(x*y)和B(x*y)矩阵能否进行A*B运算的充要条件是是否满足
A.y==B.x,如果满足,则会得到矩阵C(A.x*B.y),这次运算进行的乘法的次数是A,x*A.y*B.y.下面就考虑如何进行
实现,首先括号里面是优先计算的,也就是说我们刚开始要计算的是最内层的括号里面的表达式,也就是在碰到第一个“)”
进行运算的表达式,每碰到一个”)“,就要进行一次矩阵运算,因此可以考虑用栈这种数据结构来实现,碰到”)“就进行
矩阵运算,把运算得到的矩阵再压入栈中,对于每一个矩阵,需要维护的信息是它的x和y,矩阵的类型可以用数组下标来区分。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <string>
#include <queue>
#include <stack>
using namespace std;
const int maxn=30;
struct nod
{
    int x;
    int y;
};
nod mat[maxn];
stack<nod> sta;
int main()
{
    int n,i;
    cin>>n;
    char s;
    int a,b;
    char  q[100];
    memset(mat,0,sizeof(mat));
    while(n--)
    {
        cin>>s>>a>>b;
        int i=s-'A';
        mat[i].x=a;
        mat[i].y=b;
    }
    int sum;
    while(scanf("%s",q)!=EOF)
    {
        sum=0;
        int l=strlen(q);
        for( i=0;i<l;i++)
        {
            if(q[i]=='(') continue;
            if(q[i]>='A'&&q[i]<='Z')
            {
              int k=q[i]-'A';
              sta.push(mat[k]);
            }
            if(q[i]==')')
            {
                nod m,k,w;
                m=sta.top();
                sta.pop();
                k=sta.top();
                sta.pop();
                if(k.y!=m.x)
                    break;
                w.x=k.x,w.y=m.y;
                sta.push(w);
                sum+=k.x*k.y*m.y;
            }
          }
           if(i==l) cout<<sum<<endl;
           else cout<<"error"<<endl;
      }
    return 0;
}

UVA442 栈的更多相关文章

  1. 【UVa-442】矩阵链乘——简单栈练习

    题目描述: 输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法的次数.如果乘法无法进行,输出error. Sample Input 9 A 50 10 B 10 20 C 20 5 D 30 35 E ...

  2. UVA442 Matrix Chain Multiplication 矩阵运算量计算(栈的简单应用)

    栈的练习,如此水题竟然做了两个小时... 题意:给出矩阵大小和矩阵的运算顺序,判断能否相乘并求运算量. 我的算法很简单:比如(((((DE)F)G)H)I),遇到 (就cnt累计加一,字母入栈,遇到) ...

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

    Description   Matrix Chain Multiplication  Matrix Chain Multiplication  Suppose you have to evaluate ...

  4. UVa442 Matrix Chain Multiplication(栈)

    #include<cstdio>#include<cstring> #include<stack> #include<algorithm> #inclu ...

  5. UVa442 Matrix Chain Multiplication

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

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

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

  7. Uva442

    https://vjudge.net/problem/UVA-442 思路: 1)当遇到左括号将字母进栈,遇到右括号将字母出栈. 2) isalpha() 判断一个字符是否是字母 int isalph ...

  8. 通往全栈工程师的捷径 —— react

    腾讯Bugly特约作者: 左明 首先,我们来看看 React 在世界范围的热度趋势,下图是关键词“房价”和 “React” 在 Google Trends 上的搜索量对比,蓝色的是 React,红色的 ...

  9. Java 堆内存与栈内存异同(Java Heap Memory vs Stack Memory Difference)

    --reference Java Heap Memory vs Stack Memory Difference 在数据结构中,堆和栈可以说是两种最基础的数据结构,而Java中的栈内存空间和堆内存空间有 ...

随机推荐

  1. Python核心编程(第八章)--条件和循环

    如果一个复合语句(if子句,while或for循环)的代码仅仅包含一行代码,可以和前面的语句写在同一行上:   elif语句(else-if) 条件表达式(三元操作符) X if C else Y 计 ...

  2. 青蛙的约会(POJ 1061 同余方程)

    青蛙的约会 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 103802   Accepted: 20198 Descript ...

  3. 搭建rac对单实例的MAA

    一:实验环境 系统:redhat 4 三台计算机rac1,rac2,dg. --其中rac为主库,单实例为备库 已在虚拟机里搭建好集群环境(rac1,rac2); dg计算机里还没有建任何数据库(只安 ...

  4. 用root帐号切换其他帐号提示 su: warning: cannot change directory to /home/oracle: Permission denied

    用root帐号切换其他帐号提示: 出错原因: 基本上是根目录或者是/home/oracle目录权限的问题 解决办法: 更改根目录权限为755,并保证对应用户主目录的所属用户和所属组一致和用户名一致. ...

  5. commons-pool2-中的一些配置

      /**                     * 连接失效检测相关                     */                    // 空闲时进行连接测试,会启动异步evi ...

  6. UNIX网络编程--ioctl操作(十七)

    一.概述 在本书中有两个地方都对这个函数进行了介绍,其实还有很多地方需要这个函数.ioclt函数传统上一直作为纳西而不适合归入其他精细定义类别的特性的系统接口.网络程序(特别是服务器程序)经常在程序启 ...

  7. MOUNT MACBOOK DISK (OSX / HFS+) ON UBUNTU 12.04 LTS WITH READ/WRITE

    MOUNT MACBOOK DISK (OSX / HFS+) ON UBUNTU 12.04 LTS WITH READ/WRITE So you want to mount your HFS+ ( ...

  8. bzoj1681[Usaco2005 Mar]Checking an Alibi 不在场的证明

    Description A crime has been comitted: a load of grain has been taken from the barn by one of FJ's c ...

  9. 迅雷API:实现文件下载

     今天到迅雷公司的SDK文档网站上逛了逛,竟然发现它们已经提供了完备的API接口,我心中不禁大喜,但是SDK资料中的原版开发文件已经很难找到了,幸运的是我在github上搜索到了所需的文件,在这里我已 ...

  10. 深入super,看Python如何解决钻石继承难题

    1.   Python的继承以及调用父类成员 python子类调用父类成员有2种方法,分别是普通方法和super方法 假设Base是基类 class Base(object): def __init_ ...