ZOJ 1094 Matrix Chain Multiplication

来源:互联网 发布:织梦cms使用手册 编辑:程序博客网 时间:2024/05/19 17:59
    #include <iostream>      #include <string>      using namespace std;      static int matrix[26][2];      void init() //初始化数据    {          short n=0;          char ch;          cin>>n;          for (int i=0;i<n;i++) {              cin>>ch;              cin>>matrix[ch-'A'][0]>>matrix[ch-'A'][1];          }          return ;      }      long func(string str)     {          long result=0;          int pos=0;          int stack[26][2]={0};//stack用于存储要计算的数据        for (int i=0;i<str.length();i++) //对输入的矩阵乘式进行分析        {              if ((str[i]>='A')&&(str[i]<='Z')) //当移动到矩阵名时            {                  stack[pos][0]=matrix[str[i]-'A'][0];  //将矩阵行列数放入stack                stack[pos][1]=matrix[str[i]-'A'][1];                  pos++;  //pos移动到下一个一维数组            }              if (str[i]==')')//跳过"(",只分析")"             {                  if (stack[pos-1][0]==stack[pos-2][1])//如果)前的2个矩阵满足相乘条件                 {                      result+=stack[pos-1][0]*stack[pos-1][1]*stack[pos-2][0];  //得出结果                    stack[pos-2][1]=stack[pos-1][1];  //将第二个乘积数赋值给第一个乘积数,方便下一次运算                    pos--;  //pos此时移动到上一个一维数组                }                 else return -1;              }          }          if (pos==2) //循环结束后若pos为2 说明还有一次乘法运算未实行        {              if (stack[pos-1][0]==stack[pos-2][1]) result+=stack[pos-1][0]*stack[pos-1][1]*stack[pos-2][0];             else return -1;        }          return result;      }      int main() {          int t[2];          string str;          long result;          init();          while (cin>>str)         {              result=func(str);              if (result==-1)                  cout<<"error"<<endl;              else                  cout<<result<<endl;          }          return 0;      }   

0 0