题解 | #矩阵乘法计算量估算完美解决括号中有两个以上值#

矩阵乘法计算量估算

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

N = int(input())
m = []
mdict = {}
for i in range(N):
    mdict[chr(ord('A')+i)]=list(map(int,input().strip().split()))
 
s = input()
temp = []
result = 0
for i in s:
    if i != ')':
        temp.append(i)
    else:
        mlist = []
        while temp[-1]!='(':
            mlist.append(temp.pop())
        temp.pop()
        tempi = mdict[mlist[-1]]
        A = mlist[0]
        for i in range(len(mlist)-2, -1, -1):   #最后一个已经被初始化为tempi的值,这里应该从-2开始,假设CB的长度为2,2-2为0,这是遍历取出的值就是C,B*C
            B = mlist[i]
            result += tempi[0]*mdict[B][1]*tempi[1]
            tempi = [tempi[0],mdict[B][1]]
        mdict[A]=tempi
        temp.append(A)          
         
 
print(result)

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务