#include <iostream>
#include <map>
#include <stack>
#include <cctype>
#include <string>
using namespace std;
typedef struct
{
int m_row;
int m_column;
char m_identy;
}Matrix;
int countMultiTimes(stack<Matrix>& ope_stack, Matrix *m_in, Matrix &stack_top, Matrix &element, int n);
int Uva442()
{
int n;
while(cin >> n)
{
stack<Matrix> dict_m;
Matrix *m_in = new Matrix[n + 1];
for(int i = 0; i < n; i++)
cin >> m_in[i].m_identy >> m_in[i].m_row >> m_in[i].m_column;
m_in[n].m_identy = 'A' + n; // store the variable.
string expre;
while(cin >> expre)
{
int count_mul = 0;
int len_expre = expre.length();
Matrix element;
int count = 1; // indicate for error
for(int j = 0; j < len_expre; j++)
{
element.m_identy = expre[j];
element.m_row = m_in[expre[j] - 'A'].m_row;
element.m_column = m_in[expre[j] - 'A'].m_column;
if(element.m_identy == '(')
{
dict_m.push(element);
}
else if(element.m_identy == ')')
{
Matrix stack_top = dict_m.top();
dict_m.pop();
dict_m.pop();
// remain a character
if(!dict_m.empty())
{
Matrix stack_top_2nd = dict_m.top();
if(stack_top_2nd.m_identy != '(' && stack_top_2nd.m_identy != ')')
{
dict_m.pop();
count = countMultiTimes(dict_m, m_in, stack_top_2nd, stack_top, n);
count_mul += count;
}
else
{
dict_m.push(stack_top);
}
}
else
dict_m.push(stack_top);
}
else
{
// have one
if (!dict_m.empty())
{
Matrix stack_top = dict_m.top();
if (stack_top.m_identy != '(' && stack_top.m_identy != ')')
{
dict_m.pop();
count = countMultiTimes(dict_m, m_in, stack_top, element, n);
count_mul += count;
}
else
{
dict_m.push(element);
}
}
else
{
dict_m.push(element);
}
}
if(count == 0)
break;
}
if(!count)
cout << "error" << endl;
else
cout << count_mul << endl;
while(!dict_m.empty())
{
dict_m.pop();
}
}
if(!dict_m.empty())
dict_m.pop();
delete []m_in;
}
return 0;
}
int countMultiTimes(stack<Matrix> &dict_m, Matrix *m_in, Matrix &stack_top, Matrix &element, int n)
{
int count = 0;
int index_A = stack_top.m_identy - 'A';
int index_B = element.m_identy - 'A';
if(stack_top.m_column == element.m_row)
{
count = stack_top.m_row * stack_top.m_column * element.m_column;
stack_top.m_row = stack_top.m_row;
stack_top.m_column = element.m_column;
dict_m.push(stack_top);
}
return count;
}
UVa 442: Matrix Chain Multiplication
最新推荐文章于 2022-01-02 20:07:43 发布