您的位置:首页 > 大数据 > 人工智能

矩阵链表(Matrix Chain Multiplication)

2018-03-13 16:51 375 查看
#include <iostream>
#include<vector>
#include<map>
#include<string>
#include<algorithm>
#include<cstdio>
#include<stack>

using namespace std;

//#define LOCAL

struct Matrix{
int a,b;
Matrix(int a=0,int b=0):a(a),b(b){}
}m[26];

stack<Matrix> s;

int main() {
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int n;
cin>>n;    //输入一共n个矩阵
for(int i=0;i<n;i++){
string name;
cin>>name;
int k=name[0]-'A';
cin>>m[k].a>>m[k].b;
}            //输入n的矩阵的名字以及规格

string expr;
while(cin>>expr){
int len=expr.length();
bool error=false;
int ans=0;
for(int i=0;i<len;i++){
if(isalpha(expr[i]))
s.push(m[expr[i]-'A']);//将矩阵名字为expr[i]的矩阵存入栈
else if(expr[i]==')'){
Matrix m2=s.top();
s.pop();
Matrix m1=s.top();
s.pop();
if(m1.b!=m2.a){
error=true;
break;
}                                //读到")"则出栈两个矩阵并计算运算次数
ans+=m1.a*m1.b*m2.b;
s.push(Matrix(m1.a,m2.b));   //将两个矩阵相乘的结果矩阵入栈
}
}
if(error)printf("error\n");
else 
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithms