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

矩阵乘法计算量估算

https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b

import java.util.*;

// 想不出好的解决思路,暂时硬解。利用栈处理括号带来的计算优先级的变化
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int n = Integer.parseInt(in.nextLine());
            int[][] arrs = new int[n][2];
            for (int i = 0; i < n; i++) {
                String[] split = in.nextLine().split(" ");
                arrs[i][0] = Integer.parseInt(split[0]);
                arrs[i][1] = Integer.parseInt(split[1]);
            }
            String com = in.nextLine();
            System.out.println(count(arrs, com));
        }
    }

    public static int count(int[][] arrs, String com) {
        List<String> stack = new ArrayList<>();
        int n = com.length(), off = 0, total = 0;
        for (int i = 0; i < n; i++) {
            if (com.charAt(i) == '(') {
                stack.add(com.charAt(i) + "");
            } else if (Character.isLetter(com.charAt(i))) {
                stack.add(arrs[off][0] + "#" + arrs[off][1]);
                off++;
            } else {
                List<String> list = new ArrayList<>();
                while (!stack.get(stack.size() - 1).equals("(")) {
                    list.add(0, stack.remove(stack.size() - 1));
                }
                stack.remove(stack.size() - 1);
                String[] temp = compute(list);
                total += Integer.parseInt(temp[0]);
                stack.add(temp[1]);
            }
        }
        total += Integer.parseInt(compute(stack)[0]);
        return total;
    }

    public static String[] compute(List<String> list) {
        int t = 0;
        String[] res = new String[2];
        if (list.size() == 1) {
            res[0] = "0";
            res[1] = list.get(0);
        }
        String start = list.remove(0);
        while (!list.isEmpty()) {
            String cur = list.remove(0);
            String[] s_ = start.split("#"), c_ = cur.split("#");
            Integer one = Integer.parseInt(s_[0]);
            Integer two = Integer.parseInt(s_[1]);
            Integer three = Integer.parseInt(c_[1]);
            t += one * two * three;
            start = one + "#" + three;
        }
        res[0] = t + "";
        res[1] = start;
        return res;
    }
}

全部评论

相关推荐

06-23 18:25
沈阳大学 Java
HR已读不回,是我说话方式不对吗?
大白之主:你是串子吗? hr: 我们不招人了,把岗位挂着boss只是因为我闲得慌
点赞 评论 收藏
分享
Rena1ssance_:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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