经典指数          
原因
2285
浏览数
0
收藏数
 

矩阵乘法的运算量与矩阵乘法的顺序强相关。例如:    A是一个50×10的矩阵,B是10×20的矩阵,C是20×5的矩阵 计算A*B*C有两种顺序:((AB)C)或者(A(BC)),前者需要计算15000次乘法,后者只需要3500次。 编写程序计算不同的计算顺序需要进行的乘法次数     输入描述: 输入多行,先输入要计算乘法的矩阵个数n,每个矩阵的行数,列数,总共2n的数,最后输入要计算的法则 输出描述: 输出需要进行的乘法次数 输入例子: 3 50 10 10 20 20 5 (A(BC)) 输出例子: 3500

     举报   纠错  
 
切换
1 个答案
这道题看似容易,其实蛮多细节需要注意,弄了一下午终于搞定!!! import java.util.LinkedList; import java.util.Scanner; /** * 矩阵的计算量估计 */ public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { int n = scan.nextInt(); int[][] matrix = new int[n][2]; for (int i = 0; i < n; i++) { matrix[i][0] = scan.nextInt(); matrix[i][1] = scan.nextInt(); } String expression = scan.next(); int result = calculateMultiplyingCount(matrix, expression); System.out.println(result); } scan.close(); } // 注意与四则运算的相似和不同的地方,这里只有乘法,所以不需要判断优先级,从左到右即可 // 栈中是存矩阵的行和列 //若矩阵表达式为(A(BC(D(EF)))),首先将表达式化成(A(X(D(Y)))),然后通过找")"依次计算 private static int calculateMultiplyingCount(int[][] matrix, String expression) { int result = 0; LinkedList stack = new LinkedList(); int index = 0; for (int i = 0; i < expression.length(); i++) { char item = expression.charAt(i); if (Character.isLetter(item)) { //若为一个矩阵 if (!stack.isEmpty()&&stack.peek() != -1) { //栈顶不为"("时,计算矩阵并合并 int col = stack.pop(); int row = stack.pop(); int col2 = matrix[index][1]; result += row * col * col2; stack.push(row); stack.push(col2); } else { stack.push(matrix[index][0]); stack.push(matrix[index][1]); } index++; } else if (item == '(') stack.push(-1); else if (item == ')') { int col1 = stack.pop(); //弹出栈顶的矩阵 int row1 = stack.pop(); stack.pop(); //弹出"(" if (stack.size() <= 1) return result; if (stack.peek() != -1) { //若栈顶不为"(" 弹出栈顶矩阵并计算 stack.pop(); //col2 排在前面的矩阵 int row2 = stack.pop(); result += row2 * row1 * col1; row1 = row2; } stack.push(row1); stack.push(col1); } } return result; } }
 
切换
撰写答案
扫描后移动端查看本题