uva 442 - Matrix Chain Multiplication

这题首先是要注意输入输出,,,输入表达式时不是n个,而是文件结束;

还有结果 不能用 long long 表示,不然会PE

这题有告诉一对括号里面最多2个元素,不用多考虑怎么样使乘的次数最少,所以就用一个栈无脑模拟一下

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <stack>
#include <ctype.h>
using namespace std;
#define N 100000
int temp;
int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        int data[N][2];
        for(int i = 0; i < n; i++)
        {
            char s[2];
            int a, b;
            scanf("%s%d%d", s, &a, &b);
            data[s[0]-'A'][0] = a;
            data[s[0]-'A'][1] = b;

        }
        string ptr;
        while(cin>>ptr)
        {
            temp = 27;
            int len = ptr.size();
            stack<int> s;
            int ans = 0;
            int flag = 0;
            for(int j = 0; j < len; j++)
            {
                if(isupper(ptr[j]))
                    s.push(ptr[j]-'A');
                if(ptr[j]=='(')
                    s.push(-1);
                if(ptr[j]==')')
                {
                    int num[4], cnt = 0;
                    while(s.top()!=-1)
                    {
                        num[cnt++] = s.top();
                        s.pop();
                    }
                    s.pop();
                    if(cnt==2)
                    {
                        int a = num[1];
                        int b = num[0];
                        if(data[a][1]==data[b][0])
                        {
                            ans += data[a][0]*data[a][1]*data[b][1];
                            data[temp][0]=data[a][0];
                            data[temp][1]=data[b][1];
                            s.push(temp);
                            temp++;
                        }
                        else
                        {
                            flag = 1;
                            break;
                        }
                    }
                    if(cnt==1)
                        s.push(num[0]);
                }
            }
            if(flag)
                printf("error\n");
            else
                printf("%d\n", ans);
        }
    }
    return 0;
}



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值