POJ-2246(模拟矩阵相乘)

题目:http://poj.org/problem?id=2246

题目本身没什么难度,只不过不同风格的程序写出来不一样,这里我用了递归降解 + 异常:递归降解是求解算术运算的利器;当矩阵维数不匹配时,抛出异常,然后递归栈自动回退到main中的catch,栈上的局部变量也会自动析构,感觉这个风格有点pythonic呢


#include <cstring>
#include <string>
#include <iostream>
using namespace std;

typedef long long LL;
struct DimensionError{};
struct Result{
	//row, column and calculation already done to get the result matrix
	LL row, col, cal;
	Result(){}
	Result(LL r, LL c, LL s) : row(r), col(c), cal(s){}
	Result& operator *= (const Result& other){
		if(col != other.row) throw DimensionError();
		*this = Result(row, other.col, cal + other.cal + row * col * other.col);
		return *this;
	}
};

int matrix[26][2];

string::size_type findMatch(const string& s, string::size_type left)
{
	int cnt = 0;
	for(; true; ++left){
		if(s[left] == '(') ++cnt;
		else if(s[left] == ')' && --cnt == 0) break;
	}
	return left;
}
Result work(const string& s)
{
	string::size_type left = s.find('(');
	if(left == string::npos){//"A" or "A..."
		Result res(matrix[s[0] - 'A'][0], matrix[s[0] - 'A'][1], 0);
		for(int i = 1; i < s.size(); ++i){
			res *= Result(matrix[s[i] - 'A'][0], matrix[s[i] - 'A'][1], 0);
		}
		return res;
	}
	//find left's matcher
	Result res;
	string::size_type right = findMatch(s, left);
	if(left != 0){
		res = work(s.substr(0, left));
		res *= work(s.substr(left + 1, right - left - 1));
	}
	else res = work(s.substr(1, right - 1));
	if(right + 1 != s.size()) res *= work(s.substr(right + 1));
	return res;
}

int main()
{
	int n, r, c, i;
	string s;

	memset(matrix, -1, sizeof(matrix));
	cin >> n;
	for(i = 0; i < n; ++i){
		cin >> s >> r >> c;
		matrix[s[0] - 'A'][0] = r;
		matrix[s[0] - 'A'][1] = c;
	}
	while(cin >> s){
		//check if s contains char that does not appear in input
		for(i = 0; i < s.size(); ++i){
			if(matrix[s[i] - 'A'][0] < 0 || matrix[s[i] - 'A'][1] < 0) break;
		}
		if(i != s.size()){
			cout << "error\n";
			continue;
		}
		//figure out total multiplications
		try{
			cout << work(s).cal << "\n";
		}catch(DimensionError e){
			cout << "error\n";
		}
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值