uva 442 Matrix Chain Multiplication

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <map>
#define rep(i,n) for (int i=0;i<n;i++)
#define Max(a,b) a>b?a:b
#define Min(a,b) a<b?a:b
#define INF 0x7fffffff
#define LL long long
using namespace std;
string str;
int n;
typedef pair<int,int> pr;
map<char,pr>m;
void init()
{
    m.clear();
    for(int i=0;i<n;++i){
        char ch;
        int row,col;
        cin>>ch>>row>>col;
        pr tmp(row,col);
        m[ch]=tmp;
    }
}

int solve()
{
    int sum=0;
    if(str.size()==1) return 0;
    stack<char>st;
    map<char,pr>m1(m);
    for(int i=0;i<str.size();++i)
    {
        st.push(str[i]);
        bool cal=true;
        while(st.size()>1&&cal)
        {
            cal=false;
            char ch1=st.top();
            st.pop();
            char ch2=st.top();
            st.pop();
            if(ch1!='('&&ch1!=')'&&ch2!='('&&ch2!=')')
            {
                if(m1[ch1].first!=m1[ch2].second) return -1;
                sum+=m1[ch2].first*m1[ch2].second*m1[ch1].second;
                m1[ch2].second=m1[ch1].second;
                st.pop();
                st.push(ch2);
                cal=true;
            }
            else if(ch1==')'){
                st.push(ch2);
                cal=true;
            }
            else
            {
                st.push(ch2);
                st.push(ch1);
            }
        }
    }
    return sum;
}
int main()
{
    while(cin>>n)
    {
        init();
        while(cin>>str)
        {
            int ans=solve();
            if(ans==-1) puts("error");
            else
            cout<<ans<<endl;
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值