zoj 1094 Matrix Chain Multiplication 栈应用

//利用stack计算表达式

//类似计算中序表达式那样,用两个栈,一个存字母,一个存符号

//这题要自己存入*号,要用一个变量储存之前输入的符号,判断是否要把*入栈

//如果前一个符号是(,则不需要。

#include <iostream>

#include <stack>

#include <cstdio>

using namespace std; 



struct info

{

    int row, col;

    info() {}

    info (int row, int col)

    {

        this->row = row;

        this->col = col;

    }

}; 



const int N = 30;

stack<char> oprator;

stack<info> matrix; 



info a[N];

int n; 



int main()

{

    char c, s, last;

    int ans = 0;

    info num1, num2;

    bool isError;

    while (cin >> n)

    {

        for (int i = 0; i < n; i++)

            cin >> c >> a[i].row >> a[i].col; 



        isError = false;

        getchar();

        last = '(';

        while (scanf("%c", &c) != EOF)

        {

            if (c == '\n')

            {

                if (isError)

                    cout << "error" << endl;        

                else        

                    cout << ans << endl;

                while (!matrix.empty())

                    matrix.pop();

                while (!oprator.empty())

                    oprator.pop();

                isError = false;

                ans = 0;

                last = '(';

                continue;

            }

            if (isError)

                continue;

            if (c == '(')

            {

                if (last != c)

                    oprator.push('*');

                oprator.push(c);

                last = c;

            }

            else if (c == ')')

            {

                s = oprator.top();

                oprator.pop();

                while (s != '(')

                {

                    num1 = matrix.top();

                    matrix.pop();

                    num2 = matrix.top();

                    matrix.pop();

                    if (num2.col != num1.row)

                        isError = true;

                    else

                    {

                        ans += num2.row*num2.col*num1.col;

                        matrix.push(info(num2.row, num1.col));

                    }

                    s = oprator.top();

                    oprator.pop();

                }

                last = '0';

            }

            else

            {

                if (last != '(')

                    oprator.push('*');

                matrix.push(info(a[c-'A'].row, a[c-'A'].col));

                last = c;

            }

        }

    }

    return 0;

}

你可能感兴趣的:(Matrix)