HDU 1082 矩阵乘法次数计算 写了半天搞定,很有成就感啊

这个思想本来不难,实现起来感觉有点复杂,容易出错。调试了搞定。有成就感。、

#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int row[26], col[26];
char str[10000];
int count(int *a, int n)
{
	int flag = 0;
	if(n == 2)
		return 0;
	for(int i = 1 ; i < n-1; i += 2)
	{
		if(a[i] != a[i+1])
		{
			flag = 1;
			break;
		}
	}
	if(flag == 1)
		return -1;
	int mul = a[0];
	for(int i = 1; i < n; i += 2 )
	{
		mul *= a[i];
	}
	return mul;
}
int main()
{
	int t; 
	cin >> t;
	char temp;
	for(int i = 0 ;i < t ; i++)
	{
		getchar(); //重要
		scanf("%c", &temp);  
		scanf("%d%d", &row[temp-'A'], &col[temp-'A']);
	}
	getchar();
	while(gets(str))
	{
		int n = strlen(str);
		if(n == 1)
		{
			cout << "0" << endl;
			continue;
		}

		stack<char> stk;
		int sum = 0;
		int flag = 0;
		for(int i = 0; i < n; i++)
		{
			if(str[i] != ')' )
			{
				if(isalpha(str[i]))
				{
					stk.push((char)row[str[i] - 'A']);
					stk.push((char)col[str[i] - 'A']);
				}
				if(str[i] == '(')
					stk.push('(');
			}
			if(str[i] == ')' || i == n-1)
			{
				int cnt = 0;
				int a[10000];
				while(!stk.empty())
				{
					if(stk.top() == '(')
					{
						stk.pop();
						break;
					}
					a[cnt++] = (int)stk.top();
					stk.pop();
				}
				reverse(a, a+ cnt);
				if(!stk.empty())
				{
					stk.push(a[0]);
					stk.push(a[cnt-1]);
				}
				int mul  = 1;
				mul = count(a, cnt);
				if(mul == -1)
				{
					flag = 1;
					break;
				}
				else
					sum += mul;
			}
			if(flag == 1)
				break;
		}
		if(flag == 1)
			cout << "error" << endl ;
		else
			cout << sum << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值