题解 | 矩阵乘法计算量估算

矩阵乘法计算量估算

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.hasNextLine()) { // 注意 while 处理多个 case
            String ll = in.nextLine();
            int n = Integer.parseInt(ll);
            int[][] juzhen = new int[n][2];
            for (int i = 0; i < n; i++) {
                String[] temp = in.nextLine().split(" ");
                juzhen[i][0] = Integer.parseInt(temp[0]);
                juzhen[i][1] = Integer.parseInt(temp[1]);
            }
            String faze = in.nextLine();
            System.out.println(function(juzhen, faze));
        }
    }
    public static int function(int[][] juzhen, String yusuan) {
        int result = 0;
        Stack<int[]> stack = new Stack<>();
        for (int i = 0; i < yusuan.length(); i++) {
            if (yusuan.charAt(i) == '(') {

            } else if (yusuan.charAt(i) == ')') {
                int[] lastjuzhen = stack.pop();
                int[] nearjuzhen = stack.pop();
                result = result + lastjuzhen[0] * lastjuzhen[1] * nearjuzhen[0];
                stack.push(new int[] {nearjuzhen[0], lastjuzhen[1]});
            } else {
                stack.push(juzhen[yusuan.charAt(i) - 'A']);
            }
        }
        return result;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务