Matrix Chain Multiplication UVA - 442

2 篇文章 0 订阅

#include <bits/stdc++.h>
using namespace std;
struct Matrix
{
    int m;
    int n;
    void setM(int m,int n)
    {
        this->m=m;
        this->n=n;
    }
    bool prok(Matrix & a)
    {
        return a.m==n;
    }
    int count_pro (Matrix & a)
    {
        return m*n*a.n;
    }
    Matrix& operator = (const Matrix p)
    {
        m=p.m;
        n=p.n;
        return *this;
    }
};
stack <Matrix> op;
int main ()
{
    int n;
    cin>>n;
    char x;
    Matrix a[n];
    for (int i=0;i<n;++i)
    {
        int m,n;
        cin>>x>>m>>n;
        a[i].setM(m,n);
    }
    string k;
    while(cin>>k)
    {
        bool ok=true;
        int sum=0;
        for (int i=0;i<k.length();++i)
        {
            if (k[i]=='(')
            {
                continue;
            }
            else if ('A'<=k[i]&&k[i]<='Z')
            {
                op.push(a[k[i]-'A']);
            }
            else if (k[i]==')')
            {
                Matrix b=(Matrix)op.top();op.pop();
                Matrix a=(Matrix)op.top();op.pop();
                if (a.prok(b))
                {
                    sum+=a.count_pro(b);
                    //cout<<"a b"<<a.m<<b.n<<endl;
                    Matrix c;
                    c.setM(a.m,b.n);
                    op.push(c);
                }
                else
                {
                    ok=false;
                    break;
                }
            }
        }
        while (op.size()>1)
        {
            Matrix b=(Matrix)op.top();op.pop();
            Matrix a=(Matrix)op.top();op.pop();
            if (a.prok(b))
            {
                sum+=a.count_pro(b);
                //cout<<"a b"<<a.m<<b.n<<endl;
                Matrix c;
                c.setM(a.m,b.n);
                op.push(c);
            }
            else
            {
                ok=false;
                break;
            }
        }
        if (ok)
        {
            cout<<sum<<endl;
        }
        else
        {
            cout<<"error\n";
        }
        while(!op.empty())
        {
            op.pop();
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值