ZOJ1094Matrix Chain Multiplication

没找到分类,简单题。在函数的返回值上, 和如何定位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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值