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

矩阵乘法计算量估算

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] row = new int[n];
        int[] column = new int[n];
        for (int i = 0; i < n; i++) {
            row[i] = sc.nextInt();
            column[i] = sc.nextInt();
        }
        Stack<Character> stack = new Stack<>();
        String s = sc.next();
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            StringBuilder sb = new StringBuilder();
            stack.push(s.charAt(i));
            if (s.charAt(i) == ')') {
                stack.pop();
                while (stack.peek() != '(') {
                    sb.append(stack.pop());
                }
                String s1 = sb.reverse().toString();
                int nowRow = row[s1.charAt(0) - 'A'];
                int nowColumn = column[s1.charAt(1) - 'A'];
                for (int j = 0; j < s1.length() - 1; j++) {
                    int res = row[s1.charAt(j) - 'A'] * column[s1.charAt(j + 1) - 'A'] *
                              column[s1.charAt(j) - 'A'];
                    sum += res;
                }
                stack.pop();
                stack.push(s1.charAt(0));
                row[s1.charAt(0) - 'A'] = nowRow;
                column[s1.charAt(0) - 'A'] = nowColumn;
            }
        }
        System.out.println(sum);
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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