POJ 2246 Matrix Chain Multiplication

读懂题意,模拟一下栈处理就行了,数据结构课后习题。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
struct matrix
{
    int r;
    int c;
};
matrix l,r,t;
stack<matrix> s;
int main()
{
    int n,i,j,t1,t2,ans;
    bool flag;
    matrix m[30],ts,tts;
    l.r=-1;
    r.r=-2;
    char tc,str[12000];
    scanf("%d",&n);
    getchar();
    for (i=0; i<n; i++)
    {
        scanf("%c%d%d",&tc,&t1,&t2);
        getchar();
        m[tc-'A'].r=t1;
        m[tc-'A'].c=t2;
    }
    while (1)
    {
        gets(str);
        flag=true;
        ans=0;
        if (strcmp(str,"") == 0)
            break;
        while (!s.empty())
            s.pop();
        for (i=0; str[i]; i++)
        {
            if (str[i] == '(')
            {
                s.push(l);
            }
            else if (str[i] == ')')
            {
                ts=s.top();
                s.pop();
                tts=s.top();
                s.pop();
                if (ts.r != -1 && tts.r != -1)
                {
                    if (ts.r != tts.c)
                    {
                        flag=false;
                        printf("error\n");
                        break;
                    }
                    ans+=tts.r*ts.r*ts.c;
                    t.r=tts.r;
                    t.c=ts.c;
                    s.pop();
                    s.push(t);
                }
                else if (tts.r == -1)
                {
                    s.push(ts);
                }
            }
            else
            {
                s.push(m[str[i]-'A']);
            }
        }
        if (flag)
            printf("%d\n",ans);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值