poj2246 Matrix Chain Multiplication (栈)

    技术2022-05-19  25

    题意:给定A-Z若干矩阵。以及一些表达式,根据表达式求出所有矩阵相乘的总次数。若不符合要求输出“error”

     

     

    思路:正则表达式,需要理解矩阵相乘的一些性质。

     

    学习点:

    1、栈 STL

    头文件 #include <stack>

    定义: stack<类型> s;

    操作: empty、size、top、pop、push

     

    本题在运用栈时,其中的类型竟然可以使一种结构体。开眼界了!详细见代码注释。

     

    源代码:

    #include <iostream> #include <string> #include <stack> using namespace std; struct matrix { int nRow, nCol; }; matrix nM[30]; string nExp; int matNum; bool nFlag; long ans; void funcInput(); void funcSolve(); int main() { funcInput(); funcSolve(); return 0; } void funcInput() { string nName; cin >> matNum; for (int i = 0; i != matNum; ++i) { cin >> nName; int nIndex = nName[0] - 'A'; cin >> nM[nIndex].nRow >> nM[nIndex].nCol; } } void funcSolve() { stack<char> e; //±í´ïʽջ stack<matrix> m; //Éæ¼°µÄ¾ØÕóÕ»£¬½á¹¹ÌåµÄʹÓã¬ÐÂ֪ʶµã£¡ while (cin >> nExp) { // e.clear(); m.clear(); nFlag = true; ans = 0; int len = nExp.size(); for (int i = 0; i != len; ++i) { if (nExp[i] == '(') e.push(nExp[i]); else if (nExp[i] >= 'A' && nExp[i] <= 'Z') m.push(nM[nExp[i]-'A']); else { if (e.empty()) { nFlag = false; break; } e.pop(); matrix a = m.top(); m.pop(); matrix b = m.top(); m.pop(); if (a.nRow != b.nCol) { nFlag = false; break; } ans += a.nRow * a.nCol * b.nRow; a.nRow = b.nRow; m.push(a); } } if (nFlag) cout << ans << endl; else cout << "error" << endl; } }  


    最新回复(0)