矩阵链乘 Matrix Chain Multiplication

题目链接: https://www.luogu.com.cn/problem/UVA442

题意:

给定若干个矩阵表达式,以及涉及到的矩阵的行与列
定义矩阵相乘次数为矩阵1的行数矩阵1的列数(矩阵2的行数)矩阵2的列数
计算每个表达式的矩阵相乘次数(若不满足矩阵乘法规律输出error)

思路:

如何存储数据以及对数据进行操作是关键
对表达式的解析就用栈
然而栈中要存一个矩阵的行数与列数(不能存字符,可能会改变原先矩阵的行数与列数,总之不好操作)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
	int a;int b;
};
int n;
map<char,node>mp;
signed main()
{
	ios::sync_with_stdio(false),cin.tie(0);
	cin>>n;
	vector<ll>res;
	for(int i=1;i<=n;i++)
	{
		char ch;cin>>ch;int l,r;cin>>l>>r;
		mp[ch].a=l;
		mp[ch].b=r;
	}
	string s;
	while(cin>>s)
	{
		ll ans=0;
		bool f=true;
		stack<node>st;
		for(int i=0;i<s.size();i++)
		{
			if('A'<=s[i]&&s[i]<='Z')
			{
				st.push(mp[s[i]]);	
			}else if(s[i]==')')
			{
				node x=st.top();st.pop();
				node y=st.top();st.pop();
				if(x.a!=y.b){
					f=false;
					break;
				}else{
					ans+=y.a*x.a*x.b;
					st.push(node{y.a,x.b});
				}
			}
		}
		if(f){
			res.emplace_back(ans);
		}else{
			res.emplace_back(-1);
		}
	}
	for(int i=0;i<res.size();i++)
	{
		if(res[i]!=-1){
			cout<<res[i];
		}else{
			cout<<"error";
		}
		cout<<endl;
	}
	return 0;
}


posted @   Marinaco  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示