ACM UVA - 442 Matrix Chain Multiplication

#include <iostream>
#include <stack>
#include <string>

using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

struct matrix{
	int a, b;
	matrix(int a=0, int b = 0):a(a), b(b){}
}m[26];

stack<matrix> s;

int main(int argc, char** argv) {
	int n;
	char name;
	string operation;
	while(cin >> n)
	{
		for(int i = 0; i < n; i++)
		{
			cin >> name;
			cin >> m[name-'A'].a >> m[name-'A'].b;
		}
		while(cin >> operation)
		{
			bool error = false;
			int ans = 0;
			for(int i=0; i<operation.length(); i++)
			{
				if(isalpha(operation[i])) s.push(m[operation[i]-'A']);
				else if(operation[i] == ')')
				{
					matrix m2 = s.top();
					s.pop();
					matrix m1 = s.top();
					s.pop();
					if(m2.a != m1.b) {error = true; break;}
					ans += m1.a*m1.b*m2.b;
					s.push(matrix(m1.a, m2.b));
				}
			}
			if(error)
				cout << "error\n";
			else
				cout << ans << "\n";
		}
	}
	return 0;
}

每日AC 使用栈完成矩阵的乘运算

第一次:8.17

猜你喜欢

转载自blog.csdn.net/yestin_L/article/details/81784266
今日推荐