没找到分类,简单题。在函数的返回值上, 和如何定位left和right上纠结了一下。最初纳闷了一下如何让字母和x、y关联,查了下竟然有这么简单的方法。
//1094Matrix Chain Multiplication
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#define FILE_DEBUG
#ifdef FILE_DEBUG
#include <fstream>
#endif
using namespace std;
struct mat
{
int x, y;
} mat_size[30];
int mat_sum, exp_ptr;
long mul;
string exp;
struct mat Cal(void)
{
//cout << "exp_ptr " << exp_ptr << endl;
struct mat left, right;
char name;
if (exp.at(exp_ptr + 1) == '(')
{
exp_ptr ++;
left = Cal();
if (left.x == -1)
return left;
exp_ptr --;
}
else
{
name = exp.at(exp_ptr + 1);
left.x = mat_size[name - 'A'].x;
left.y = mat_size[name - 'A'].y;
}
if (exp.at(exp_ptr + 2) == '(')
{
exp_ptr += 2;
right = Cal();
if (right.x == -1)
return right;
exp_ptr -= 2;
}
else
{
name = exp.at(exp_ptr + 2);
right.x = mat_size[name - 'A'].x;
right.y = mat_size[name - 'A'].y;
}
if (left.y != right.x)
{
struct mat error;
error.x = error.y = -1;
return error;
}
//cout << "left " << left.x << " " << left.y
// << " right " << right.x << " " <<right.y << endl;
mul += left.x * left.y * right.y;
exp.erase(exp_ptr, 3);
exp.at(exp_ptr) = 'X';
//cout << "erase to " << exp << endl;
struct mat correct;
correct.x = left.x;
correct.y = right.y;
return correct;
}
int main(int argc, char *argv[])
{
#ifdef FILE_DEBUG
ifstream fin;
fin.open("input.txt");
cin.rdbuf(fin.rdbuf()); // assign file's streambuf to cin
#ifdef _C_LAN_
freopen("input.txt", "r", stdin);
#endif
#endif
#ifdef FILE_DEBUG
ofstream fout;
fout.open("output.txt");
cout.rdbuf(fout.rdbuf()); // assign file's streambuf to cout
#ifdef _C_LAN_
freopen("output.txt", "w", stdout);
#endif
#endif
int tmp[2];
cin >> mat_sum;
char name;
for (int i = 0; i < mat_sum; i ++)
{
cin >> name >> tmp[0] >> tmp[1];
mat_size[name - 'A'].x = tmp[0];
mat_size[name - 'A'].y = tmp[1];
}
while (cin >> exp && cin.eof() == NULL)
{
if (exp.at(0) == '(')
{
//exp_ptr[0] = 1;
//exp_ptr[1] = 2;
exp_ptr = 0;
mul= 0;
if (Cal().x == -1)
cout << "error";
else
cout << mul;
}
else if (exp.size() <= 1)
cout << 0;
cout << endl;
}
return 0;
}