ZOJ 1094 Matrix Chain Multiplication

    #include <iostream>  
    #include <string>  
    using namespace std;  
    static int matrix[26][2];  
    void init() //初始化数据
    {  
        short n=0;  
        char ch;  
        cin>>n;  
        for (int i=0;i<n;i++) {  
            cin>>ch;  
            cin>>matrix[ch-'A'][0]>>matrix[ch-'A'][1];  
        }  
        return ;  
    }  
    long func(string str) 
    {  
        long result=0;  
        int pos=0;  
        int stack[26][2]={0};//stack用于存储要计算的数据
        for (int i=0;i<str.length();i++) //对输入的矩阵乘式进行分析
        {  
            if ((str[i]>='A')&&(str[i]<='Z')) //当移动到矩阵名时
            {  
                stack[pos][0]=matrix[str[i]-'A'][0];  //将矩阵行列数放入stack
                stack[pos][1]=matrix[str[i]-'A'][1];  
                pos++;  //pos移动到下一个一维数组
            }  
            if (str[i]==')')//跳过"(",只分析")" 
            {  
                if (stack[pos-1][0]==stack[pos-2][1])//如果)前的2个矩阵满足相乘条件 
                {  
                    result+=stack[pos-1][0]*stack[pos-1][1]*stack[pos-2][0];  //得出结果
                    stack[pos-2][1]=stack[pos-1][1];  //将第二个乘积数赋值给第一个乘积数,方便下一次运算
                    pos--;  //pos此时移动到上一个一维数组
                } 
                else return -1;  
            }  
        }  
        if (pos==2) //循环结束后若pos为2 说明还有一次乘法运算未实行
        {  
            if (stack[pos-1][0]==stack[pos-2][1]) result+=stack[pos-1][0]*stack[pos-1][1]*stack[pos-2][0]; 
            else return -1;
        }  
        return result;  
    }  
    int main() {  
        int t[2];  
        string str;  
        long result;  
        init();  
        while (cin>>str) 
        {  
            result=func(str);  
            if (result==-1)  
                cout<<"error"<<endl;  
            else  
                cout<<result<<endl;  
        }  
        return 0;  
    }   

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值