Uva - 442 - Matrix Chain Multiplication


题目比较水,用一个栈stack<pair<int, int> > exprStack; 当是字母就入栈,如果是右括号就出栈两个元素做乘法运算,再把结果压入栈。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset> 
#include <cassert> 

using namespace std;

typedef pair<int, int> mn;
map<string, mn> matrix; // 存放矩阵

int main()
{
	int n;
	scanf("%d", &n);
	// 矩阵输入并存放
	for (int i = 0; i < n; i++) {
		string s;
		int m, n;
		cin >> s >> m >> n;
		matrix[s] = mn(m, n);
	}

	string expr;
	while (cin >> expr) {
		if (expr.length() == 1) { // 只有一个的时候直接输出0
			printf("0\n");
			continue;
		}
		
		long long countOfM = 0; // 乘法次数,怕溢出用了long long
		stack<mn> exprStack; // 用来存放表达式的栈
		bool ok = true;
		for (int i = 0; i < expr.length(); i++) {
			string s = expr.substr(i, 1);
			if (isalpha(expr[i])) { // 如果是字母,就入栈
				exprStack.push(mn(matrix[s].first, matrix[s].second));
			}
			else if (s == ")") { // 如果是右括号,就出栈两个矩阵做计算
				// 注意先出栈的是B,后出栈的是A,然后AB相乘
				int Bm = exprStack.top().first;
				int Bn = exprStack.top().second;
				exprStack.pop();
				int Am = exprStack.top().first;
				int An = exprStack.top().second;
				exprStack.pop();
				if (An == Bm) {
					countOfM += (long)Am * (long)An * (long)Bn;
					exprStack.push(mn(Am, Bn));
				}
				else {
					ok = false;
					break;
				}
			}
		}
		if (ok) {
			cout << countOfM << endl;
		}
		else {
			cout << "error\n";
		}
	}
	
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值