矩阵链乘(Matrix Chain Multiplication)

2023-05-16

Matrix Chain Multiplication
Time Limit:3000MS Memory Limit:Unknown 64bit IO Format:%lld & %llu

Submit Status

Description

Download as PDF

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  
【分析】

       解析表达式:可以用一个栈来完成:遇到字母时入栈,遇到右括号时出栈并计算,然后结果入栈。因为输入保证合法,括号无须入栈。

简单的表达式解析可以借助栈来完成。

用C++语言编写程序,代码如下:

#include<iostream>
#include<stack>
#include<string>
using namespace std;

struct Matrix {
	int a, b;
	Matrix(int a = 0, int b = 0) : a(a), b(b) {}
} m[26];

stack<Matrix> s;

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string name;
		cin >> name;
		int k = name[0] - 'A';
		cin >> m[k].a >> m[k].b;
	}

	string expr;
	while (cin >> expr) {
		int len = expr.length();
		bool error = false;
		int ans = 0;
		for (int i = 0; i < len; i++) {
			if (isalpha(expr[i])) {
				s.push(m[expr[i] - 'A']);
			}
			else if (expr[i] == ')') {
				Matrix m2 = s.top(); s.pop();
				Matrix m1 = s.top(); s.pop();
				if (m1.b != m2.a) {
					error = true;
					break;
				}
				else {
					ans += m1.a * m1.b * m2.b;
					s.push(Matrix(m1.a, m2.b));
				}
			}
		}
		if (error)
			cout << "error" << endl;
		else
			cout << ans << endl;
	}
	return 0;
}

用java语言编写程序,代码如下:

import java.util.Scanner;
import java.util.Stack;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		Matrix[] m = new Matrix[26];
		int n = input.nextInt();
		for(int i = 0; i < n; i++) {
			String name = input.next();
			int k = name.charAt(0) - 'A';
			int r = input.nextInt();
			int c = input.nextInt();
			m[k] = new Matrix(r, c);
		}
		
		Stack<Matrix> s = new Stack<Matrix>();
		String expr;
		while(input.hasNext()) {
			expr = input.next();
			int len = expr.length();
			boolean error = false;
			int ans = 0;
			for(int i = 0; i < len; i++) {
				 char temp = expr.charAt(i);
				 if(temp >= 'A' && temp <= 'Z')
					 s.push(m[temp - 'A']);
				 else if(temp == ')'){
					 Matrix m2 = s.pop();
					 Matrix m1 = s.pop();
					 if(m1.c != m2.r) {
						 error = true;
						 break;
					 }
					 else {
						 ans += m1.r * m1.c * m2.c;
						 s.push(new Matrix(m1.r, m2.c));
					 }
				 }
			 }
			 if(error)
				 System.out.println("error");
			 else
				 System.out.println(ans);
		}
	}
	
	static class Matrix {
		int r, c;
		public Matrix(int r, int c) {
			this.r = r;
			this.c = c;
		}
	}
}



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

矩阵链乘(Matrix Chain Multiplication) 的相关文章

  • firewalld 命令大全

    1 firewalld的基本使用 启动 xff1a systemctl start firewalld 查看状态 xff1a systemctl status firewalld 停止 xff1a systemctl disable fir
  • vscode通过文件名查找文件的方法

    vscode通过文件名查找文件的方法 这篇文章给大家分享的是有关vscode通过文件名查找文件的方法的内容 小编觉得挺实用的 xff0c 因此分享给大家做个参考 一起跟随小编过来看看吧 按快捷键ctrl 43 p可以弹出一个小窗 xff0c
  • HTML几种设置水平居中和垂直居中的方式

    水平居中 1 平居中设置 定宽块状元素 当被设置元素为 块状元素 时用 text align xff1a center 就不起作用了 xff0c 这时也分两种情况 xff1a 定宽块状元素和不定宽块状元素 这一小节我们先来讲一讲定宽块状元素
  • 【Django网络安全】如何正确设置跨域

    原文作者 xff1a 我辈李想 版权声明 xff1a 文章原创 xff0c 转载时请务必加上原文超链接 作者信息和本声明 Django网络安全 Django网络安全 如何正确设置跨域 Django网络安全 如何正确防护CSRF跨站点请求伪造
  • 我怎么能只懂得使用Redis呢?(一)

    前言 最近在回顾 amp 学习Redis相关的知识 xff0c 也是本着分享的态度和知识点的记录在这里写下相关的文章 希望能帮助各位读者学习或者回顾到Redis相关的知识 xff0c 当然 xff0c 本人才疏学浅 xff0c 在学习和写作
  • 统计回文子串

    1054 统计回文子串 分数 2 时间限制 xff1a 1 秒 内存限制 xff1a 32 兆 特殊判题 xff1a 否 标签 字符串处理回文串 题目描述 现在给你一个字符串S xff0c 请你计算S中有多少连续子串是回文串 输入格式 输入
  • 小明养猪的故事

    1064 小明养猪的故事 分数 1 时间限制 xff1a 1 秒 内存限制 xff1a 32 兆 特殊判题 xff1a 否 标签 递推 题目描述 话说现在猪肉价格这么贵 xff0c 小明也开始了养猪生活 说来也奇怪 xff0c 他养的猪一出
  • 找新朋友

    1079 找新朋友 分数 1 时间限制 xff1a 1 秒 内存限制 xff1a 32 兆 特殊判题 xff1a 否 标签 简单数学题公约数 题目描述 新年快到了 xff0c 天勤准备搞一个聚会 xff0c 已经知道现有会员N人 xff0c
  • 生物节律

    1084 生物节律 分数 2 时间限制 xff1a 1 秒 内存限制 xff1a 32 兆 特殊判题 xff1a 否 标签 数学题 题目描述 有些人相信 xff0c 人从出生开始就有三个生物周期 这三个生物周期分别是体力 xff0c 情绪和
  • 鸡兔同笼

    鸡兔同笼 已知鸡和兔的总数量为n xff0c 总腿数为m 输入n和m xff0c 依次输出鸡的数目和兔的数目 如果无解 xff0c 则输出No answer 样例输入 xff1a 14 32 样例输出 xff1a 12 2 样例输入 xff
  • 赌徒

    1097 赌徒 分数 2 时间限制 xff1a 1 秒 内存限制 xff1a 32 兆 特殊判题 xff1a 否 标签 查找二分查找 题目描述 有n个赌徒打算赌一局 规则是 xff1a 每人下一个赌注 xff0c 赌注为非负整数 xff0c
  • 排列(permutation)

    排列 xff08 permutation xff09 用1 2 3 xff0c xff0c 9组成3个三位数 abc xff0c def 和 ghi xff0c 每个数字恰好使用一次 xff0c 要求 abc def ghi 61 1 2
  • SQL Server Management Studio 使用方法手记

    本方法只记录自己的操作方法 xff0c 仅供参考 一 下载安装 SQL Server Management Studio V15 0 18424 0 xff0c 链接 xff1a https download csdn net downlo
  • 蛇形填数(矩阵)

    蛇形填数 在 n x n 方针里填入 1 2 xff0c xff0c n x n xff0c 要求填成蛇形 例如 xff1a n 61 4时方阵为 xff1a 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4 上
  • WERTYU

    Problem 1343 WERTYU Time Limit 1000 mSec Memory Limit 32768 KB Problem Description A common typing error is to place the
  • 分子量(Molar Mass)

    Molar mass Time limit 3 000 seconds An organic compound is any member of a large class of chemical compounds whose molec
  • 数数字(Digit Counting)

    Digit Counting Time limit 3 000 seconds Trung is bored with his mathematics homeworks He takes a piece of chalk and star
  • 周期串(Periodic Strings)

    周期串 Periodic Strings 如果一个字符串可以由某个长度为k的字符串重复多次得到 xff0c 则称该串以k为周期 例如 xff0c abcabcabcabc以3为周期 xff08 注意 xff0c 它也以6和12为周期 xff
  • 谜题(Puzzle)

    Puzzle Time limit 3 000 seconds Puzzle A children 39 s puzzle that was popular 30 years ago consisted of a 5x5 framewhic
  • 纵横字谜的答案(Crossword Answers)

    Crossword Answers Time limit 3 000 seconds Crossword Answers A crossword puzzle consists of a rectangular grid of black

随机推荐

  • DNA序列(DNA Consensus String)

    DNA Consensus String Time limit 3 000 seconds Figure 1 DNA Deoxyribonucleic Acid is the molecule which contains the gene
  • 古老的密码(Ancient Cipher)

    Ancient Cipher Time limit 3 000 seconds Ancient Roman empire had a strong governmentsystem with various departments incl
  • Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing

    原文转载自 sunny2038 的CSDN博客文章 原文地址 最近在看Java xff0c 在编译写书上一个例子时 xff0c 由于书上的代码只有一部分 xff0c 于是就自己补了一个内部类 结果编译时出现 xff1a No enclosi
  • 瑞星微开发工具下载镜像的配置方法?

    如何根据 parameter txt 建立配置表 xff1f 首先我们来看下 parameter txt 的内容 xff1a CMDLINE mtdparts 61 rk29xxnand 0x00002000 64 0x00004000 u
  • 特别困的学生(Extraordinarily Tired Students)

    Extraordinarily Tired Students Time limit 3 000 seconds When a student is too tired he can 39 t help sleeping in class e
  • 骰子涂色(Cube painting)

    Cube painting We have a machine for painting cubes It is supplied with three different colors blue red and green Each fa
  • 盒子(Box)

    Box Time limit 3 000 seconds Ivan works at a factory that produces heavy machinery He hasa simple job he knocks up woode
  • 循环小数(Repeating Decimals)

    Repeating Decimals Time limit 3 000 seconds Repeating Decimals The decimal expansion of the fraction 1 33 is wherethe is
  • 反片语(Ananagrams)

    反片语 Ananagrams 输入一些单词 xff0c 找出所有满足如下条件的单词 xff1a 该单词不能通过字母重排 xff0c 得到输入文本中的另外一个单词 在判断是否满足条件时 xff0c 字母不分大小写 xff0c 但在输出时应保留
  • 集合栈计算机(The SetStack Computer)

    The SetStack Computer Time limit 3 000 seconds 题目是这样的 xff1a 有一个专门为了集合运算而设计的 集合栈 计算机 该机器有一个初始为空的栈 xff0c 并且支持以下操作 xff1a PU
  • 代码对齐(Alignment of Code)

    Alignment of Code Time Limit 4000 2000 MS Java Others Memory Limit 32768 32768 K Java Others Total Submission s 958 Acce
  • Ducci序列(Ducci Sequence)

    Ducci Sequence Time limit 3 000 seconds A Ducci sequence is a sequence of n tuples of integers Given an n tuple of integ
  • 卡片游戏(Throwing cards away I)

    Problem B Throwing cards away I Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at
  • 交换学生(Foreign Exchange)

    Problem E Foreign Exchange Input standard input Output standard output Time Limit 1 second Your non profit organization
  • CAN通信物理容错测试checklist

    CAN通信物理容错测试checklist 工作项目中 xff0c 我们有时有些产品CAN总线功能 xff0c 一般情况下我们必须要满足以下几种状况的测试项才算符合要求 一 CAN H与CAN L短路 判定标准 xff1a 短接故障发生后 x
  • 对称轴(Symmetry)

    Symmetry Time limit 3 000 seconds The figure shown on the left is left right symmetric as it is possible to fold the she
  • 打印队列(Printer Queue)

    Printer Queue Time limit 3 000 seconds 分析 首先记录所求时间它在队列中的位置 xff0c 用一个队列存储这些任务的优先级 xff0c 同时也创建一个队列存储对应任务一开始的位置 xff0c 那么当我们
  • 更新字典(Updating a Dictionary)

    Updating a Dictionary Time Limit 1000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description In th
  • 铁轨(Rails)

    Rails Time limit 3 000 seconds Rails There is a famous railway station in PopPush City Country there is incredibly hilly
  • 矩阵链乘(Matrix Chain Multiplication)

    Matrix Chain Multiplication Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description