Uva 442 - Matrix Chain Multiplication(模拟)

题目链接 https://cn.vjudge.net/problem/UVA-442

【题意】
输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法次数。如果乘法无法执行,输出error。假定A是m×n矩阵,B是n×p矩阵,则A×B的结果是一个m×p矩阵,乘法次数是m×n×p,当左边矩阵的列不等于右边矩阵的行时,乘法就无法进行。保证输入合法并且每个括号里面只包含两个矩阵。

【思路】
用一个栈来模拟计算过程,因为输入保证合法,所以不需要把括号压入栈中。只要遇到的是矩阵就把它压入栈中,当碰到右括号的时候,把栈的顶端的两个矩阵取出,然后计算乘法次数,同时把得到的矩阵再压回栈中。

#include<bits/stdc++.h>
using namespace std;

const int maxn=30;

struct node{
    int r,c;
    node(int rr=0,int cc=0):r(rr),c(cc){}
};

int n;
node rec[maxn];

int main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    cin>>n;
    while(n--){
        char ch;
        int r,c;
        cin>>ch>>r>>c;
        rec[ch-'A']=node(r,c);
    }
    string s;
    while(cin>>s){
        stack<node> st;
        int ans=0;
        bool ok=true;

        for(int i=0;i<s.length();++i){
            if('A'<=s[i] && s[i]<='Z') st.push(rec[s[i]-'A']);
            else if(')'==s[i]) {
                node x=st.top();st.pop();
                node y=st.top();st.pop();
                if(y.c!=x.r) {
                    ok=false;
                    break;
                }
                ans+=y.r*y.c*x.c;
                st.push(node(y.r,x.c));
            }
        }
        if(ok) cout<<ans<<endl;
        else cout<<"error\n";
    }
    return 0;
}
posted @ 2018-03-27 17:22  不想吃WA的咸鱼  阅读(137)  评论(0编辑  收藏  举报