矩阵链乘uva442(栈)

这道题思路很简单,遇到字母就入栈,遇到‘)’出栈。

#include <iostream>
#include <stdio.h>
#include <stack>
using namespace std;

struct node
{
    int le, ri;
}alph[26];
bool judge(char c)
{
    if(c>='A'&&c<='Z')
        return true;
    return false;
}
int main()
{
    for(int i=0; i<26; i++)
        alph[i].le = alph[i].ri = 0;
    int n, left, right;
    scanf("%d", &n);
    char alp;
    while(n--)
    {
        cin >> alp;
        scanf("%d", &alph[alp-'A'].le);
        scanf("%d", &alph[alp-'A'].ri);
    }
//    for(int i=0; i<26; i++)
//        cout << alph[i].le << " " <<  alph[i].ri << endl;
    string str;
    stack<node> st;
    while(cin >> str)
    {
       int ans = 0, flag = 0;
       int len = str.length();
       for(int i=0; i<len; i++)
       {
           if(judge(str[i]))
            st.push(alph[str[i]-'A']);
            else if(str[i]==')')
            {
                node a = st.top();
                st.pop();//后
                node b = st.top();
                st.pop();//前
                if(b.ri!=a.le)
                {
                  flag = 1;  break;
                }
                else
                {ans += b.le*b.ri*a.ri;node c; c.le = b.le; c.ri = a.ri;st.push(c);}
            }
       }
       if(!flag)
        cout << ans << endl;
        else
            cout << "error\n";
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值