题解 | #矩阵乘法计算量估算#
矩阵乘法计算量估算
https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b
import java.io.IOException;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
int count = Integer.parseInt(sc.nextLine());
String[] input = new String[count];
for(int i = 0; i < count; ++i){
input[i] = sc.nextLine();
}
String expression = sc.nextLine();
Stack<String> stack = new Stack();
int result = 0;
for (int i = 0, j = 0; i < expression.length(); ++i) {
char c = expression.charAt(i);
if(c == '('){
// 遇到左括号,左括号入栈
stack.push(c + "");
} else if(Character.isLetter(c)){
// 遇到字母,对应的矩阵大小入栈
stack.push(input[j++]);
}else {
// 遇到右括号,计算结果并入栈
String matrix2 = stack.pop();
String matrix1 = stack.pop();
if(stack.peek().equals("(")){
stack.pop();
}
stack.push(matrix1.split(" ")[0] + " " + matrix2.split(" ")[1]);
result += Integer.parseInt(matrix1.split(" ")[0]) * Integer.parseInt(matrix1.split(" ")[1]) * Integer.parseInt(matrix2.split(" ")[1]);
}
}
System.out.println(result);
}
}
查看16道真题和解析