华为机试-070-中等-HJ70.矩阵乘法计算量估算
一、描述
1.1、输入描述
输入多行,先输入要计算乘法的矩阵个数n,每个矩阵的行数,列数,总共2n的数,最后输入要计算的法则
计算的法则为一个字符串,仅由左右括号和大写字母(‘A’~‘Z’)组成,保证括号是匹配的且输入合法!
1.2、输出描述
输出需要进行的乘法次数
二、示例
2.1、示例1
输入:
3
50 10
10 20
20 5
(A(BC))
输出:
3500
三、答案(java)
3.1、方法一
package com.tzq.hwod;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt();
int a[][] = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = in.nextInt();
a[i][1] = in.nextInt();
}
String s = in.next();
Stack<Integer> stack = new Stack(); // 存放矩阵行数和列数
int sum = 0;
for (int i = s.length() - 1, j = n - 1; i >= 0; i--) {
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') { // 属于字母则把相应的矩阵列数和行数入栈
stack.push(a[j][1]);
stack.push(a[j][0]);
j--;
} else if (s.charAt(i) == '(') { // 括号:推出计算
int x0 = stack.pop(), y0 = stack.pop(); // 矩阵尺寸x0*y0
int x1 = stack.pop(), y1 = stack.pop(); // 矩阵尺寸x1*y1
sum += x0 * y0 * y1; // 两个矩阵的乘法次数为x0*y0*y1或x0*x1*y1(其中y0==x1)
stack.push(y1); // 把相乘后得到的矩阵列数入栈
stack.push(x0); // 把相乘后得到的矩阵行数入栈
}
}
System.out.println(sum);
}
}
}
四、答案(python 3)
4.1、方法一
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#计算式的题目,考出入栈处理括号
#先摘抄优秀答案:
#按照出入栈处理括号的思路,自己重写如下代码。
while True:
try:
n = int(input())
mdict = {}
for i in range(n):
mdict[chr(ord('A')+i)] = list(map(int, input().strip().split()))## 用strip()先去掉可能隐藏的末尾空格。再split(),防止map不过去
s = input()
result = 0
temp = []
for i in s:
if i != ')':#不遇到')'就一直压栈
temp.append(i)
else: #直接遇到')',把前两个弹出来计算乘法运算量
C = temp.pop()
B = temp.pop()
temp.pop()#弹掉前括号'('
result+= mdict[B][0] * mdict[B][1] * mdict[C][1]
mdict[B] = [mdict[B][0], mdict[C][1]]#把当前乘积的结果存储起来
temp.append(B)#把当前乘积结果入栈
#因为有最外圈括号,弹完所有')'即完成整个算式的结果
print(result)
except:
break