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

矩阵乘法计算量估算

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static int res = 0;
    static int matrix[][];
    static int multiplyNum(int[] m1, int[] m2){
        return m1[0] * m1[1] * m2[1];
    }
    static int[] multiply(int[] m1, int[] m2){
        return new int[]{m1[0],m2[1]};
    }
    static int findMatchParent(String s, int idx){
        int count = 1;
        for(int i=idx+1;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='(')count++;
            else if(c==')') count--;
            if(count==0) return i;
        }
        return -1;
    }

    static int[] dfs(String s){
        int[] preMatrix = null;
        int[] nextMatrix;
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='('){
                int headI = i+1;
                i = findMatchParent(s,i);
                nextMatrix = dfs(s.substring(headI,i));

            }else{
                nextMatrix = matrix[c-'A'];
            }

            if(preMatrix==null){
                preMatrix = nextMatrix;
            }else{
                res += multiplyNum(preMatrix,nextMatrix);
                preMatrix = multiply(preMatrix, nextMatrix);

            }
        }
        return preMatrix;
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int n = in.nextInt();
        matrix = new int[n][2];
        for(int i=0;i<n;i++){
            matrix[i][0] = in.nextInt();
            matrix[i][1] = in.nextInt();
        }

        String line = in.next();
        dfs(line.substring(1,line.length()-1));
        System.out.println(res);
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务