UVA - 442-Matrix Chain Multiplication

题目传送门

#include <iostream>
#include <stdio.h>
#include <stack>
#define MAXN 36
#define MAXL 11000
char temp[MAXL];
struct Node
{
	int a;
	int b;//存储矩阵长和宽
}matrix[MAXN];//26个字母对应26个矩阵,个人喜欢36这个数字开成这样而已。。。
using namespace std;
stack <Node>s;//定义一个存储矩阵的栈
int main(void)
{
	int T;//矩阵的数量

	scanf("%d", &T);
	while (T--)
	{
		char ch;
		int temp_a, temp_b;

		//getchar();
		//scanf("%c %d %d", &ch, &temp_a, &temp_b);
		cin >> ch >> temp_a >> temp_b;//不想用%c了太难用了!!!
		matrix[ch - 'A'].a = temp_a;//因为字母有规律,因此我把它转化成数字来方便我把存储在一个结构数组中
		matrix[ch - 'A'].b = temp_b;
	}
	while (scanf_s("%s", temp, MAXL) != EOF)
	{
		int sum = 0;
		bool ok = true;//如果不能继续乘下去了

		for (int i=0; temp[i]; i++)
			if (temp[i] == ')')
			{//遇到')'就弹出两个矩阵来相乘
				Node x;

				int x1 = s.top().a;
				int x2 = s.top().b;
				s.pop();
				int y1 = s.top().a;
				int y2 = s.top().b;
				s.pop();
				if ( x1 != y2)
				{//矩阵的乘法是单向的!!!
					ok = false;
					break;
				}
				/*else if (x2 == y1)
				{
					sum += x1 * x2*y2;
					x.a = x1;
					x.b = y2;
					s.push(x);
				}*/
				else if (x1 == y2)
				{//AB和BA是不一样的,所以注意顺序!
					sum += x1 * x2*y1;
					x.a = y1;
					x.b = x2;
					s.push(x);//计算出来之后把计算出来的值压入栈中
				}
			}
			else if (temp[i] >= 'A'&&temp[i] <= 'Z')
			{//如果遇到字母就把这个字母对应的矩阵压入栈
				s.push(matrix[temp[i] - 'A']);
			}
		if (ok)//如果能够正确的乘完,那就输出结果
			printf("%d\n", sum);
		else
			printf("error\n");
	}
	

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值