uva 442

原題

簡單題, 計算矩陣鏈乘需要的數乘次數

這類題最近做了幾道, 都是採用遇到左括號忽略, 遇到右括號出棧, 其他字符壓棧的操作

大概是表達式題的通用算法了把

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <list>
#include <cassert>
#include <iomanip>

using namespace std;
const int MAXN 	= 100000;
const int BASE 	= 100000000;
typedef long long LL;

/*
uva 442

*/

struct matrix{
	int row,col;
	matrix(){ }
	matrix(int _row, int _col){
		row = _row;
		col = _col;	
	}
} ;

map<char,matrix> M;
stack<matrix> S;

matrix Pop(){
	matrix res = S.top();
	S.pop();
	return res;
}

int main(){
//	freopen("input2.txt","r",stdin);
	int N;
	char ch, str[MAXN];
	matrix m;
	cin >> N;
	for(int i=0; i<N; i++){
		cin >> ch >> m.row >> m.col;
		M[ch] = m;
	}
	while( scanf("%s",str)!=EOF ){
		int len = strlen(str), sum = 0;
		bool isError = false;
		for(int i=0; i<len; i++){
			if( isalpha(str[i]) ){
				S.push(M[str[i]]);
			}
			if( str[i]==')' ){
				matrix m2 = Pop();	
				matrix m1 = Pop();
				if( m1.col!=m2.row ){
					isError = true;
					break;
				}
				S.push(matrix(m1.row,m2.col));
				sum += m1.row*m1.col*m2.col;	
			}
		}
		if( !isError ){
			cout << sum << endl;
		}else{
			cout << "error" << endl;
		}
		
	} 
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章