版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HEYIAMCOMING/article/details/81117999
题目描述:
矩阵乘法的运算量与矩阵乘法的顺序强相关。
例如:
A是一个50×10的矩阵,B是10×20的矩阵,C是20×5的矩阵
计算A*B*C有两种顺序:((AB)C)或者(A(BC)),前者需要计算15000次乘法,后者只需要3500次。
编写程序计算不同的计算顺序需要进行的乘法次数
Java实现:
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext()) {
String nStr=scanner.nextLine();
int n=Integer.parseInt(nStr);
int[][] matrix=new int[n][2];
for (int i = 0; i < n; i++) {
String str=scanner.nextLine();
String[] tmpArray=str.split(" ");
matrix[i][0]=Integer.parseInt(tmpArray[0]);
matrix[i][1]=Integer.parseInt(tmpArray[1]);
}
String expression=scanner.nextLine();
int result=calculateMutiplyCount(matrix,expression);
System.out.println(result);
}
scanner.close();
}
public static int calculateMutiplyCount(int[][] matrix, String expression) {
int result=0;
Stack<Integer> stack=new Stack<Integer>();
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();
int row2=stack.pop();
result+=row2*row1*col1;
row1=row2;
}
stack.push(row1);
stack.push(col1);
}
}
return result;
}
}
知识点:
- 栈里存放的是每个矩阵的行数和列数