UVA442 Matrix Chain Multiplication 矩阵运算量计算(栈的简单应用)

栈的练习,如此水题竟然做了两个小时。。。

题意:给出矩阵大小和矩阵的运算顺序,判断能否相乘并求运算量。

我的算法很简单:比如(((((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了一下。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值