栈+字符串 | HJ70 矩阵乘法计算量估算
# 最优代码 while True: try: n = int(input()) arr = [] order = [] res = 0 for i in range(n): arr.append(list(map(int, input().split()))) f = input() for i in f: if i.isalpha(): order.append(arr[ord(i) - 65]) elif i == ')' and len(order) >= 2: a = order.pop() b = order.pop() res += b[0] * b[1] * a[1] order.append([b[0], a[1]]) print(res) except: break # 我的代码 def get_calcu_times(arrays, expr): q = [] # 栈中记录入栈的矩阵大小 res = 0 # 返回计算次数 for ch in expr: if ch >= 'A' and ch <= 'Z': # 是矩阵则把该矩阵大小入栈 q.append(arrays[ord(ch)-65]) elif ch == ')': # 遇到右括号,出栈两个矩阵计算,并入栈计算结果 arr2_n, arr2_m = q.pop() arr1_n, arr1_m = q.pop() res += arr1_n * arr1_m * arr2_m q.append((arr1_n, arr2_m)) return res def main(): arrays = [] # 记录各个矩阵大小 num = int(input()) # 输入矩阵个数 for i in range(num): n, m = input().split(' ') arrays.append((int(n), int(m))) expr = input() # 输入表达式 return get_calcu_times(arrays, expr) print(main())#栈#
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107