题解 | #矩阵乘法计算量估算# 还是和四则运算一样递归了

矩阵乘法计算量估算

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

#矩阵a = [3,2]  3*2矩阵

#M[a,b,c,d]  计算模块  用栈计算也可以
def compute_ct(M):
    m1 = M[0]
    ct = 0
    i = 1
    while i<len(M):
        m2 = M[i]
        ct += m1[0]*m2[0]*m2[1]
        m1 = [m1[0],m2[1]]
        i +=1
    return ct , m1

#递归模块
p = 0
def compute_s(s,matrixs):
    global p
    l = len(s)
    compute_stack=[]
    ct = 0
    while p < l:
        if s[p] == '(':
            p +=1
            # 计算括号中的结果 返回ct和 矩阵
            sub_ct, sub_m1 = compute_s(s,matrixs)
            ct += sub_ct
            compute_stack.append(sub_m1)

        elif s[p] == ')':
            break

        else:
            d = ord(s[p])-ord('A')     
            if d in range(27):
                compute_stack.append(matrixs[d])

        p +=1
    
    mct , m1 = compute_ct(compute_stack)
    ct += mct
    
    return ct , m1

        



n = int(input())
matrixs= []
for _ in range(n):
    temp = list(map(int,input().split()))
    matrixs.append(temp)

compute_str = input()
compute_stack = []

ct = compute_s(compute_str, matrixs)[0]

print(ct)

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务