题解 | #矩阵乘法计算量估算#
矩阵乘法计算量估算
https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b
import java.util.*; // 注意类名必须为 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(); // 二维数据表示输入的矩阵行列 // 如input[0][0] 表示第一个矩阵A的行,input[0][1] 表示第一个矩阵A的列 // 如input[1][0] 表示第二个矩阵B的行,input[1][1] 表示第二个矩阵B的列 int[][] input = new int[n][2]; for (int i = 0; i < n; i++) { input[i][0] = in.nextInt(); input[i][1] = in.nextInt(); } Stack<Object> stack = new Stack<>(); String str = in.next(); int count = 0; for (char c : str.toCharArray()) { if ('(' == c) { stack.push(c); } else if (')' == c) { // 右括号需要计算 int col2 = (int) stack.pop(); // 弹出第二个矩阵的列数 int row2 = (int) stack.pop(); // 弹出第二个矩阵的行数 int col1 = (int) stack.pop(); // 弹出第一个矩阵的列数 int row1 = (int) stack.pop(); // 弹出第一个矩阵的行数 stack.pop(); // 弹出左括号 count += row1 * col1 * col2; // 计算乘法次数,并累加到总次数中 stack.push(row1); // 将结果的行数压入栈中 stack.push(col2); // 将结果的列数压入栈中 } else { // 字母,压入对应的行列 stack.push(input[c - 'A'][0]); stack.push(input[c - 'A'][1]); } } System.out.println(count); } } }