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

矩阵乘法计算量估算

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

import java.math.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.stream.*;
import java.util.regex.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = in.nextInt();
        Map<Character, Integer[]> map = new HashMap<>();
        for (int i = 0; i < count; i++) {
            map.put((char)('A' + i)
                    , new Integer[] {in.nextInt(), in.nextInt()});
        }

        String rule = in.next();
        LinkedList<Character> stack = new LinkedList<>();

        long total = 0l;

        for (int i = 0; i < rule.length(); i++) {
            char c = rule.charAt(i);
            if (c == '(' || Character.isAlphabetic(c)) {
                stack.push(c);
            } else if (c == ')') {
                List<Character> list = new ArrayList<>();
                while (!stack.isEmpty() && stack.peek() != '(') {
                    list.add(stack.pop());
                }
                // (
                stack.pop();

                Collections.reverse(list);
                Integer[] m = map.get(list.get(0));
                for (int j = 1; j < list.size(); j++) {
                    Integer[] currm = map.get(list.get(j));
                    total += (m[0] * m[1] * currm[1]);
                    m = new Integer[]{m[0], currm[1]};
                }

                char key = (char)('A' + count++);
                stack.push(key);
                map.put(key, m);
            }
        }

        System.out.println(total);
    }
}


全部评论

相关推荐

04-25 19:29
已编辑
宁波大学 运营
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
玉无心❤️:发照片干啥 发简历啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务