UVa 442 Matrix Chain Multiplication

~~~题目链接~~~


题目大意:给出一些矩阵,现在给出一个带括号的表达式, 要求求出这些矩阵相乘最后得多少


思路:用stack模拟,从表达式的右边开始入栈, 当不是左括号是入栈, 是左括号时表达式出栈,直到遇到右括号。



#include <iostream>
#include <string>
#include <stack>
using namespace std;
struct node
{
    int x, y;
}matrix[10002];
int n = 0;
int multip(node a, node b)
{
    if(a.y != b.x) return -1;
    return a.x*a.y*b.y;
}
int main()
{
    int i = 0, k = 0, sum = 0, flag = 0;
    stack<char> s;
    string str;
    char ch = 0;
    cin>>n;
    for(i = 0; i<n; i++)
    {
        cin>>ch;
        cin>>matrix[ch-'A'].x>>matrix[ch-'A'].y;
    }
    while(cin>>str)
    {
        flag = sum = 0;
        k = 26;
        int len = str.size();
        for(i = len-1; i>-1 && !flag; i--)
        {
            if(str[i] != '(')
                s.push(str[i]);
            else
            {
                while(1 && !flag)
                {
                    int num = s.top()-'A';
                    node a = matrix[num];
                    s.pop();
                    if(s.top() == ')')
                    {
                        s.pop();
                        s.push(num+'A');
                        break;
                    }
                    node b = matrix[s.top()-'A'];
                    s.pop();
                    int c = multip(a, b);
                    if(c == -1) flag = 1;
                    else sum += c;
                    matrix[k].x = a.x;
                    matrix[k].y = b.y;
                    s.push(k+'A');
                    k++;
                }
            }
        }
        if(flag)
            cout<<"error"<<endl;
        else
            cout<<sum<<endl;
    }
    return 0;
}


你可能感兴趣的:(UVa 442 Matrix Chain Multiplication)