zoj1094 Matrix Chain Multiplication

来源:互联网 发布:js map 遍历对象数组 编辑:程序博客网 时间:2024/06/11 19:59
  1. //zoj1094   Matrix Chain Multiplication
  2. //Accepted 1094 C++ 00:00.01 848K
  3. #include <cstdio>
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7. struct matrix{ int row,col;}m[26],t[26];
  8. int sum;
  9. int index(char c){   return c-'A';}
  10. void backtrack(string s)
  11. {
  12.        int i,j,k;
  13.        if (s.length()==4){
  14.               i = index(s[1]), j = index(s[2]);
  15.               if (m[i].col==m[j].row){
  16.                      sum += m[i].row*m[j].row*m[j].col;
  17.                      cout << sum << endl;
  18.               }else cout << "error" << endl;
  19.               return;
  20.        }
  21.        for (k=1; s[k]!=')'; ++k);
  22.        i = index(s[k-2]), j = index(s[k-1]);
  23.        if (m[i].col==m[j].row){
  24.               sum += m[i].row*m[j].row*m[j].col;
  25.               m[i].col = m[j].col;
  26.               s.erase(k-1,2);
  27.               s.erase(k-3,1);
  28.               backtrack(s);
  29.        }else cout << "error" << endl;
  30. }
  31. int main()
  32. {
  33. #ifdef ONLINE_JUDGE
  34. #else
  35.        freopen("1094.txt","r",stdin);
  36. #endif
  37.        int i,n;
  38.        cin>>n;
  39.        char c;
  40.        for (i=0; i<n; ++i)
  41.               cin >> c >> t[i].row >> t[i].col;
  42.        string s;
  43.        while (cin >> s){
  44.               if (s.length()==1){
  45.                      cout << 0 << endl;
  46.                      continue;
  47.               }
  48.               for (i=0; i<n; ++i) m[i].row = t[i].row, m[i].col = t[i].col;
  49.               sum = 0;
  50.               backtrack(s);
  51.        }
  52. #ifdef ONLINE_JUDGE
  53. #else
  54.        fclose(stdin);
  55. #endif
  56.        return 0;
  57. }
原创粉丝点击