uva 442 矩阵链乘

来源:互联网 发布:剑雨江湖仙器进阶数据 编辑:程序博客网 时间:2024/05/22 03:26
// 题意:输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法的次数。假定A和m*n的,B是n*p的,那么AB是m*p的,乘法次数为m*n*p  

// 算法:用一个栈。遇到字母时入栈,右括号时出栈并计算,然后结果入栈。因为输入保证合法,括号无序入栈

//  Created by Chenhongwei in 2015.//  Copyright (c) 2015 Chenhongwei. All rights reserved.#include"iostream"#include"cstdio"#include"cstdlib"#include"cstring"#include"climits"#include"queue"#include"cmath"#include"map"#include"set"#include"vector"#include"stack"#include"sstream"#include"algorithm"using namespace std;typedef long long ll;typedef pair<int,int> P;P m[30];int main(){//ios::sync_with_stdio(false);// freopen("in.txt","r",stdin);//freopen("out.txt","w",stdout);int n;scanf("%d\n",&n);for(int i=1;i<=n;i++){char ch;int a,b;scanf("%c %d %d\n",&ch,&a,&b);m[ch-'A'+1].first=a;m[ch-'A'+1].second=b;}string s;while(getline(cin,s)){stack<P> stk;ll ans=0;int flag=1;for(int i=0;i<s.size();i++){if(s[i]=='(')continue;else if(isalpha(s[i]))stk.push(m[s[i]-'A'+1]);else if(s[i]==')'){P x,y,temp;x=stk.top();stk.pop();y=stk.top();stk.pop();if(x.first!=y.second){flag=0;printf("error\n");break;}else{ans+=y.first*y.second*x.second;temp.first=y.first;temp.second=x.second;stk.push(temp);}}}if(flag==1)cout<<ans<<endl;}return 0;}


0 0