题解 | #矩阵乘法计算量估算#
矩阵乘法计算量估算
https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b
栈中保存字母
import java.util.Scanner;
import java.util.Stack;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
int[][] nums = new int[n][2];
for (int i = 0; i < n; i++) {
nums[i][0] = in.nextInt();
nums[i][1] = in.nextInt();
}
String str = in.next();
Stack<Character> stack = new Stack<>();
int ans = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ')') {
char left = '\0';
while (stack.peek() != '(') {
char right = stack.pop();
left = stack.pop();
ans += nums[left - 'A'][0] * nums[right - 'A'][0] * nums[right - 'A'][1];
nums[left - 'A'][1] = nums[right - 'A'][1];
}
stack.pop();
stack.push(left);
} else {
stack.push(c);
}
}
System.out.println(ans);
}
}
}
