题解 | #矩阵乘法计算量估算#
矩阵乘法计算量估算
https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b
借鉴了一下大佬的思路,大佬没写代码,我贴一下
思路:
遍历计算规则字符串rule,是左括号不管,是矩阵入栈,是右括号出栈两个,
通过定义好的multi函数运算得到乘法次数times和新矩阵new_M,新矩阵入栈,
res加上乘法次数,遍历完输出res
def multimes(): def multi(M1,M2): return M1[0]*M2[0]*M2[1],[M1[0],M2[1]] n = int(input()) matrix = [] for _ in range(n): matrix.append(list(map(int,input().split()))) rule = input() stack = [] res = 0 for i in rule: if 'A'<=i<='Z': stack.append(matrix[ord(i)-65]) elif i==')': M2 = stack.pop() M1 = stack.pop() times,new_M = multi(M1,M2) res+=times stack.append(new_M) print(res) multimes()