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

括号内字母可大于2

import java.util.*;

public class Main {
    public static void main(String[] args) {

        // 输入
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(); // 矩阵个数

        // 矩阵数组
        Matrix[] matrices = new Matrix[n];
        for (int i = 0; i < n; i++) {
            int row = in.nextInt(); // 矩阵行数
            int col = in.nextInt(); // 矩阵列数
            matrices[i] = new Matrix(row, col);
        }

        String formula = in.next(); // 读取运算式(next()跳过换行符)

        int crossNum = 0; // 总运算量
        Stack<Character> stack = new Stack<>(); // 用于处理括号和矩阵

        for (int i = 0; i < formula.length(); i++) {
            char ch = formula.charAt(i);

            //输入为'('
            if (ch == '(') {
                stack.push(ch); // 压入左括号
            } 
            
            //输入为字母(矩阵)
            else if (ch >= 'A' && ch <= 'Z') {

                // 如果栈顶是字母(矩阵),则计算乘法,后将结果矩阵压回栈
                if (!stack.isEmpty() && stack.peek() != '(') {
                    char top = stack.pop();
                    crossNum += matrices[top - 'A'].cross(matrices[ch - 'A']);
                    stack.push(top); 
                } 
                // 如果栈顶不是字母(矩阵),则直接压入矩阵
                else {
                    stack.push(ch); 
                }
            } 
            
            //输入为')',弹出栈顶的矩阵
            else {
   
                char top = stack.pop();
                stack.pop(); // 弹出对应的左括号

                // 如果栈顶是字母(矩阵),则计算乘法,后将结果矩阵压回栈
                if (!stack.isEmpty() && stack.peek() != '(') {
                    char prev = stack.pop();
                    crossNum += matrices[prev - 'A'].cross(matrices[top - 'A']);
                    stack.push(prev); 
                } 
                //如果栈顶不是字母(矩阵),则直接压入矩阵
                else {
                    stack.push(top);
                }
            }
        }

        System.out.println(crossNum); // 输出总运算量
    }

    //矩阵类
    static class Matrix {
        int row;
        int col;

        public Matrix(int row, int col) {
            this.row = row;
            this.col = col;
        }

        // 计算两个矩阵相乘的运算量,并更新当前矩阵的列数
        public int cross(Matrix other) {
            int result = row * col * other.col;
            col = other.col; // 更新当前矩阵的列数
            return result;
        }
    }
}


全部评论

相关推荐

想run的马里奥在学...:这个学历帮你扫平百分之80的障碍,投就完了,这会找不到就等3月暑期一样能找到
点赞 评论 收藏
分享
白火同学:1、简历可以浓缩成一页,简历简历先要“简”方便HR快速过滤出有效信息,再要“历”用有效信息突出个人的含金量。 2、教育背景少了入学时间~毕业时间,HR判断不出你是否为应届生。 3、如果你的平台账号效果还不错,可以把账号超链接或者用户名贴到对应位置,一是方便HR知道你是具体做了什么内容的运营,看到账号一目了然,二是口说无凭,账号为证,这更有说服力。
面试被问期望薪资时该如何...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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