题解 | #矩阵乘法计算量估算#
矩阵乘法计算量估算
http://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b
改了一下其他答案,使他不必只能计算括号内两个矩阵的情况
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
tmp = [] #tmp用来按顺序存储矩阵列表
r = [] #记录左括号在tmp中的位置
for i,_s in enumerate(s):
if _s == "(":
r.append(len(tmp)
continue
elif _s != ')':
tmp.append(_s)
elif _s == ')': #遇到右括号就从左开始计算
_r = r.pop()
tt = tmp[_r:][::-1]
tmp = tmp[:_r]
if len(tt) > 1:
while len(tt)>1:
m1 = tt.pop()
m2 = tt.pop()
result+= mdict[m1][0] * mdict[m1][1] * mdict[m2][1]
mdict[m1] = [mdict[m1][0], mdict[m2][1]]
tt.append(m1)
tmp.append(tt[0])
print(result)
except:
break