栈的练习,如此水题竟然做了两个小时。。。
题意:给出矩阵大小和矩阵的运算顺序,判断能否相乘并求运算量。
我的算法很简单:比如(((((DE)F)G)H)I),遇到 (就cnt累计加一,字母入栈,遇到)减一,并出栈两个矩阵计算运算量,将计算后的矩阵压入栈。当cnt等于0时就输出运算量。
难点是当不能运算后的处理。
卡那么就其实主要是细节问题,最大的坑是里面退栈时倒着退出,没注意到结果每次计算都判断为不能计算。。。
AC代码:
#include <iostream> #include <cstdio> #include <stack> using namespace std; int const maxn = 27; struct Mat{ int x, y; }; Mat mat[maxn]; Mat multip(Mat a, Mat b) { Mat tmp; tmp.x = a.x; tmp.y = b.y; return tmp; } int main() { int n, cnt = 0, kh = 0; bool flag = true; char tmp; Mat a, b; stack <Mat> v; freopen("in", "r", stdin); cin >> n; while (n--) { cin >> tmp; tmp -= 'A'; cin >> mat[tmp].x >> mat[tmp].y; }//while while (cin >> tmp) { if (kh == 0) { flag = true; } if (flag == false) { if (tmp == '(') kh++; else if (tmp == ')') kh--; continue; } if (tmp >= 'A' && tmp <= 'Z') { v.push(mat[tmp - 'A']); }//alpha else{ if (tmp == '(') { kh++; }//( else if (tmp == ')'){ kh--; a = v.top(); v.pop(); b = v.top(); v.pop(); if (b.y != a.x) { cout << "error" << endl; cnt = 0; flag = false; continue; } cnt += b.x * a.x * a.y; v.push(multip(b, a)); }//) }//not alpha if (kh == 0) { cout << cnt << endl; cnt = 0; }//print }//while return 0; }
提交时又忘记去掉文件重定向了,wa了一下。。。