当前位置: 代码迷 >> 综合 >> Uva442 Matrix Chain Multiplication
  详细解决方案

Uva442 Matrix Chain Multiplication

热度:50   发布时间:2023-12-05 13:31:48.0

原题:

总体思路就是用栈来进行表达式解析。

代码: 

//利用栈来进行表达式解析
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<map>
#include<array>
#include<sstream>
#include<cctype>
#define endl "\n"
using namespace std;
struct Matrix
{int row,col;Matrix (int row=0,int col=0)//构造函数{this->row=row;this->col=col;}Matrix operator * (const Matrix& rhs)//矩阵乘法运算{return Matrix(row,rhs.col);}
};
bool valid(const Matrix& lhs,const Matrix& rhs)//判断矩阵相乘是否合法
{if(lhs.col==rhs.row){return true;}else{return false;}
}
void parse_stack(stack<Matrix>& calculate,Matrix& A,Matrix& B)//出栈运算
{B=calculate.top();calculate.pop();A=calculate.top();calculate.pop();
}
int main(int argc, char const *argv[])
{ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);map<char,int> catalog;//用映射来定义目录array<Matrix,30> MatrixSet;//矩阵集合数组int n;cin>>n;cin.get();string s;for(int i=0;i<n;i++){getline(cin,s);char c;stringstream ss(s);ss>>c>>MatrixSet[i].row>>MatrixSet[i].col;catalog[c]=i;}while(cin>>s){stack<Matrix> calculate;long long oper=0;//记录操作数bool vis=true;//决定整个表达式是否合法for(int i=0;i<s.length();i++){if(isalpha(s[i])){calculate.push(MatrixSet[catalog[s[i]]]);}else if(s[i]==')'){Matrix A,B;parse_stack(calculate,A,B);if(valid(A,B)){oper+=(A.row*A.col*B.col);calculate.push(A*B);}else{vis=false;break;}}}if(vis){cout<<oper<<endl;}else{cout<<"error"<<endl;}}return 0;
}

  相关解决方案