题解 | #矩阵乘法计算量估算#

矩阵乘法计算量估算

https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b

def def_multi(l):
    count = 0
    while len(l) != 1:
        la = l.pop(0)
        lb = l.pop(0)
        count += la[0]*la[1]*lb[1]
        l.insert(0, [la[0], lb[1]])
    return count, l[0]


num = int(input())
s_matrix = []
for i in range(num):
    s_matrix.append(list(map(int, input().split())))

order = input()
# 注输入的计算法则最外部若没有括号,则需要套一层括号
if order[0] != '(' and order[-1] != ')':
    order = f'({order})'


ls = []
c = 0
for i in order:
    if i.isalpha():
        ls.append(s_matrix[c])
        c += 1
    else:
        ls.append(i)

result = 0
tp = []
for line in ls:
    if line != ')':
        tp.append(line)
    else:
        # 遇到右括号
        temp = []
        while tp[-1] != '(':
            # 从右往左遍历,直到遇到左括号为止,弹出最后一个数字并存储
            temp.insert(0, tp.pop())
        tp.pop()    # 弹出左括号
        # 将左括号和右括号之间的矩阵,进行乘法计算量估算
        temp_c, temp_l = def_multi(temp)
        # 将估算后的值存储至结果集
        result += temp_c
        # 将新得到的矩阵,放入栈
        tp.append(temp_l)

print(result)

# 本人菜鸟的初次献丑,望诸位大佬不喜勿喷,多担待下,谢谢各位

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务