• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 联系
  • 订阅
  • 管理

View Post

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;
}

posted on 2011-03-19 13:22  sysuwhj  阅读(437)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3