HDOJ 1082 模拟 水
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1082
题目大意:有若干个矩阵,输入数据给出其行,列数。再给若干个计算矩阵乘法的顺序,求出以此顺序来计算矩阵乘法所需要进行的乘法次数。如果有两个矩阵不能想成,要报错。
我的方法:从左到右处理一个矩阵乘法的计算顺序。若遇到矩阵,则保存进栈。若遇到左括号,不作处理。若遇到右括号,取出栈中前两个矩阵,求它们进行乘法需要的乘法次数。
#include <iostream> #include <stack> using namespace std; const int MATRIX_LEN = 30; const int INPUT_LEN = 200; class Matrix { public: char name[2]; int row, col; }; Matrix matrices[MATRIX_LEN]; stack<Matrix> stackMatrices; int main () { int matricesNum; scanf("%d",&matricesNum); Matrix aMatrix; //读入所有矩阵,并将他们存入数组 for (int i = 0;i < matricesNum;i ++) { scanf("%s%d%d",aMatrix.name,&aMatrix.row,&aMatrix.col); int pos = aMatrix.name[0] - 'A'; matrices[pos] = aMatrix; } char input[INPUT_LEN]; //对读入的一组运算顺序进行计算 while (scanf("%s",input) != -1) { while ( ! stackMatrices.empty()) stackMatrices.pop(); int totalMultiCount = 0; int isError = 0; Matrix left, right; //将矩阵和括号存入不同的栈 for (int i = 0;i < strlen(input);i ++) { if (isalpha(input[i])) { aMatrix = matrices[ input[i] - 'A' ]; stackMatrices.push(aMatrix); continue; } //如果遇到左括号,忽略 if (input[i] == '(') continue; right = stackMatrices.top(); stackMatrices.pop(); left = stackMatrices.top(); stackMatrices.pop(); if (left.col != right.row) { isError = 1; break; } totalMultiCount += left.row * left.col * right.col; aMatrix.row = left.row; aMatrix.col = right.col; stackMatrices.push(aMatrix); } if (isError) printf("error\n"); else printf("%d\n",totalMultiCount); } return 0; }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号