UVA 442 - Matrix Chain Multiplication

本文介绍了一种利用栈来处理矩阵运算的方法。通过解析输入指令,实现矩阵相乘的操作,并考虑了各种边界情况,如矩阵无法相乘时的错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单题,利用栈来进行操作。读取指令,如果读取到的指令仅仅由一个字母组成,那么就查找我们是否已经保存了该矩阵的信息,如果保存了,那么不需要做任何的乘法操作,直接输出0,如果没有保存,那么就直接输出"error"。对于长度不为1的指令,依次读取相应的信息,如果是左括号,那么就往栈1中存入一个行列均为-1的矩阵,如果是其他的非右括号的符号,那么就存入相应的矩阵,如果读入的是右括号,那么就从栈中依次弹出矩阵到栈2,直到遇到左括号所对应的矩阵。然后对栈2中的矩阵进行处理,依次出栈2,判断是否能够进行乘法操作,如果不能进行,则输出"error",结束当前的处理,如果可以,就一直处理,同时更新总的乘法数,对于当前产生的最终结果要存入栈1,以便进行后续的计算使用。

源代码如下:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<iomanip>
using namespace std;

int n;
typedef struct matrix{
	int row, col;
	bool operator!=(matrix a){
		if (row != a.row || col != a.col) return true;
		return false;
	}
}matrix;

int main(){
	int n;
	while (cin >> n){
		vector<matrix> data;
		map<char, int> ch2ind;
		for (int i = 0; i < n; i++){
			matrix temp;
			char name;
			cin >> name >> temp.row >> temp.col;
			data.push_back(temp);
			ch2ind[name] = i;
		}
		string instruct;
		while (cin >> instruct){
			int amount = 0;
			bool flag_e = false;
			if (instruct.size() == 1){
				char aim = instruct[0];
				if (ch2ind.find(aim) != ch2ind.end()) cout << "0" << endl;
				else cout << "error" << endl;
				continue;
			}
			else{
				stack<matrix> st;
				stack<matrix> st_a;
				matrix left_k;
				left_k.row = -1;
				left_k.col = -1;
				for (int i = 0; i < instruct.size(); i++){
					if (instruct[i] == '('){
						st.push(left_k);
					}
					else if (instruct[i]!=')'){
						st.push(data[ch2ind[instruct[i]]]);
					}
					else{//')'
						while (!st.empty()&&st.top() != left_k){
							st_a.push(st.top());
							st.pop();
						}
						st.pop();
						matrix temp1 = st_a.top();
						st_a.pop();
						while (!st_a.empty()){
							matrix temp2 = st_a.top();
							st_a.pop();
							if (temp1.col != temp2.row){
								flag_e = true;
								cout << "error" << endl;
								break;
							}
							else{
								amount += temp1.row*temp1.col*temp2.col;
								temp1.col = temp2.col;
							}
						}
						if (flag_e) break;
						st.push(temp1);
					}
				}
				if (!flag_e) cout << amount << endl;
			}
		}
	}
	//system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值